PDA

View Full Version : QMYSQL - Naming a connection makes drivers unavailable



RyanR
15th September 2020, 12:38
Hey guys,

I currently have an issue with QtSql/QSqlDatabase libraries with Qt C++ on Debian with Qt Creator 5.8.2 (Qt 5.11.3 GCC 32 bit); my latest industrial software engineering project requires multiple MySQL database connections on different threads. After some research, it seems that I need to name my database connections. However whenever I add a second argument to QSqlDatabase::addDatabase, the drivers become unavailable.

The following code works fine and I can verify on the SQL CLI that the data is being received correctly:

QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL");

db.setHostName("00.00.000.000");
db.setDatabaseName("00000");
db.setUserName("00000");
db.setPassword("00000");

bool dbOk = db.open();

if(dbOk)
{
qDebug() << "Connected to Database.";

QString queryData;
queryData.sprintf("INSERT INTO `dev`.`logs` (`logid`, `timestamp`, `command`) VALUES (NULL, CURRENT_TIMESTAMP, 'Test')");

qDebug() << "Output Query Data: " << queryData << ".";

QSqlQuery query(queryData);

if(!query.isActive())
{
qDebug() << "ERROR Error with database query! " << "Last Database Error: " << db.lastError() << ". Last Query Error: " << query.lastError() << ".";

}
else
{
qDebug() << "Query is good!";
}
}

QString connection;
connection = db.connectionName();
db.close();
db = QSqlDatabase();
db.removeDatabase(connection);

But when I change:


QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL");

To:


QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL", "MyConnName");

I get "ERROR Error with database query! Last Database Error: QSqlError("", "", "") . Last Query Error: QSqlError("", "Driver not loaded", "Driver not loaded") .". Does anyone have any idea as to why this is happening?

Any help would be greatly appreciated!

Thanks,
Ryan

^NyAw^
15th September 2020, 16:26
Hi,

In line 19 you are not passing the Database to the query, so it basically worked because you only had one database connection. It is using the default Database.



QSqlQuery query(queryData,db);

RyanR
16th September 2020, 10:24
Legend, that's got it working!

Now every time I create a new thread I pass the thread ID as the database connection name, and I can have separate MySQL connections per thread.

Thanks very much for the help!