Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct
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:
now, when i execute a query, i get
Parameter count mismatcherror, 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.
the error is from
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.
To add to @Christian-Ehrlicher, I am not sure that using a file path is necessarily a good idea for a connection name.
then what should i be using?
A meaningful identifier, just the name of the database, etc. That's up to you.
yeah something unique, so i thought file path would be more unique then fine name
In any case, you should do as @Christian-Ehrlicher wrote: get the error from the failed query.
the parameter mismatch error is the text given by
And what is the query ? The one returned by lastQuery ?
prepare()was failing and i got the error from sql query at right after prepare() and it was meaningful