getting already open database connection
-
i have a table view which needs to display info from database. i'm using
QSqlDatabase
. this is how i open a db connection:auto db = QSqlDatabase::database(); db.setDatabaseName(m_sDatabasePath); if (!db.open()) error(arg(db.lastError().text());
later i use queries like this one to retrieve the info:
QSqlQuery sqlQuery(QSqlDatabase::database()); if (sqlQuery.exec(...) && sqlQuery.first()) ...
since i'm using the default connection, when i open a new database i cannot use these queries to retrieve info from old connection. i know that i should name the connections and access them via name, but...
use scenario is the following:- open db #1, issue queries, display data in view (table tab)
- open db #2, issue queries, display data in new table tab
- switch back to old tab, problem: queries are still executed on db #2 (default connection).
so i changed connection opening to this:
auto db = QSqlDatabase::addDatabase("QSQLITE", sDatabasePath); db.setDatabaseName(sDatabasePath); if (!db.open()) error(arg(db.lastError().text());
and changed the queries to this:
QSqlQuery sqlQuery(QSqlDatabase::database(m_info->getDatabasePath()));
now, when i execute a query, i get
Parameter count mismatch
error, and i'm not sure why, because before this change everything worked correctly (for default connection). -
Don't think this has something to do with the other database connection. I would take a look at the query where it fails, and check what QSqlQuery::error() and database() really returns.
-
@Christian-Ehrlicher
the error is fromQSqlQuery::lastError()
.
and it worked with default connection -
Please show the query, make sure that the db is really open at the time you're trying to execute the query.
-
Hi,
To add to @Christian-Ehrlicher, I am not sure that using a file path is necessarily a good idea for a connection name.
-
A meaningful identifier, just the name of the database, etc. That's up to you.
-
In any case, you should do as @Christian-Ehrlicher wrote: get the error from the failed query.
-
And what is the query ? The one returned by lastQuery ?
-
actually
prepare()
was failing and i got the error from sql query at right after prepare() and it was meaningful