databaseqtqsqlqueryqsqldatabase

QSqlDatabase Connecting to Multiple Databases


I am having issues attempting to connect to two different databases in one Qt Application. I have my information database that stores all the information collected by the application and the new Log database which allows me to track all the changes that occur to the Application, button presses, screen loads etc, for easy debugging after its release. Separately, the databases work perfectly, but when I try to use both of them, only one will work. I read that this could be because I wasn't naming the connections and obviously only the most recently connected database could use the default connection. However when I give the databases names they wont work at all, isOpen() will return true on both, but as soon as they attempt to execute a query I get the errors

"QSqlQuery::prepare: database not open"

"QSqlError(-1, "Driver not loaded", "Driver not loaded")"

My two database declarations are:

database_location = filepath.append("/logger.sqlite");
logDB = QSqlDatabase::addDatabase("QSQLITE", "LoggerDatabaseConnection");
logDB.setHostName("localhost");
logDB.setDatabaseName(database_location);

for the Logger Database connection and :

database_location = filepath.append("/db.sqlite");
db = QSqlDatabase::addDatabase("QSQLITE",  "NormalDB");
db.setHostName("localhost");
db.setDatabaseName(database_location);

Also when I am running the first query on the databases to see if their tables exist I am using

QSqlQuery query("LoggerDatabaseConnection");

and likewise for the normal database, but I am still getting connection issues even after declaring the database connection to run the query on.

The database used for the application is declared as a static QSqlDatabase in a namespace to create a global effect, so everyone can access it, that was a previous programmer, and I created the Log database as Singleton with a private database connection. Like I said both versions of the code work separately but when they are together they are fighting each other. I know there is a huge debate over the proper design of Singleton vs Dependecy Injection, but again the code works separately so I am happy with how it is designed for now. If there is any missing information or if you have any ideas, please let me know. Thank you.


Solution

  • QSqlQuery query("LoggerDatabaseConnection");
    

    The first parameter of the constructor is the query, not the connection name. It will use the default connection since you specified no database object.

    Try something like this:

    QSqlQuery query1("YourFirstQuery", db);
    QSqlQuery query2("YourSecondQuery", logDB);
    

    Important: Also do not forget to open and close the database before / after using it by calls to QSqlDatabase::open() and QSqlDatabase::close().