[SOLVED] Loading new database using QSqlDatabase
I have an application where I load one database, and this works fine. The problem arises when I try to load a second one.
Right now I've declared my QSqlDatabase objects globally in my header file:
QSqlDatabase m_dbSec; //this is the new one
Here I try to load the second one:
m_dbSec = QSqlDatabase();
m_dbSec = QSqlDatabase::addDatabase("QSQLITE", "database2");
bool open = m_dbSec.open();
This works fine the first time because then m_dbSec.isValid() returns false. But when I want to change my m_dbSec to a new one,
isValid() returns true and this warning is thrown:
QSqlDatabasePrivate::removeDatabase: connection 'database2' is still in use, all queries will cease to work.
I notices that both m_db and m_dbSec returns ( "database", "database2") when I run m_db/m_dbSec.connectionNames(). Is this the problem?
Since QSqlDatabase is static within your application I find a good and easy way to open the database connection once and refer to it when you use it. For example:
bool dbOpen(const QString& anyConnectionName)
QSqlDatabase db; // no need to store as global variable
db = QSqlDatabase::addDatabase("QSQLITE", anyConnectionName);
bool open = db.open();
Refer to database:
... some code
QSqlDatabase db = QSqlDatabase::database(anyConnectionName);
... some other code
This is not the answer you'd asked for, but this solution will omit the warning you mentioned above.
Thanks! As you maybe noticed, I solved it. Did almost exactly the same thing as you.
But this led me to another question. My application can now have two databases open at the same time. They are typically 2-3 GB large. What are the pros/cons of having even more databases open at the same time? Anyone have any experience with this? Thinking about memory usage and things like that. This is maybe not a Qt-specific question, but at least related to the use of QsqlDatabase.