[SOLVED] Loading new database using QSqlDatabase
-
wrote on 13 Aug 2012, 08:26 last edited by
Hi,
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_db;
QSqlDatabase m_dbSec; //this is the new one
@Here I try to load the second one:
@
if(m_dbSec.isValid())
{
m_dbSec.close();
m_dbSec = QSqlDatabase();
QSqlDatabase::removeDatabase("database2");}
m_dbSec = QSqlDatabase::addDatabase("QSQLITE", "database2");
m_dbSec.setDatabaseName(fileName);
m_dbSec.setConnectOptions("QSQLITE_BUSY_TIMEOUT");
bool open = m_dbSec.open();
return 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?
-
wrote on 13 Aug 2012, 11:06 last edited by
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:
Open Database:
@
QString connectionName1("database1");
QString connectionName2("database2");bool dbOpen(const QString& anyConnectionName)
{
QSqlDatabase db; // no need to store as global variable
db = QSqlDatabase::addDatabase("QSQLITE", anyConnectionName);
db.setDatabaseName(fileName);
db.setConnectOptions("QSQLITE_BUSY_TIMEOUT");
bool open = db.open();
return open;
}
@Refer to database:
@
{
... some codeQSqlDatabase db = QSqlDatabase::database(anyConnectionName);
QSqlQuery query(db);... some other code
}
@This is not the answer you'd asked for, but this solution will omit the warning you mentioned above.
-
wrote on 13 Aug 2012, 13:10 last edited by
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.
1/3