0

I have code that works:

QSqlDatabase db;
QSqlQuery query;
db = QSqlDatabase::addDatabase("QSQLITE");
db.setDatabaseName(directory + QDir::separator() + "db.sqlite3");
db.open();
query.exec("create table mytable (id integer)");

But, if I try to name the added database by changing line 3 to:

db = QSqlDatabase::addDatabase("QSQLITE", "db");

I get a "Driver not loaded Driver not loaded" error. I've tried editing the SQL statement to all of the following, but nothing seems to work.

query.exec("create table db.mytable (id integer)");
query.exec("create table `db`.mytable (id integer)");
query.exec("create table 'db'.mytable (id integer)");

How do I query the specific database within the connection? I can find lots of examples for the default database, but nothing for named databases.

Kenneth Vaughn
  • 435
  • 5
  • 10

1 Answers1

0

I found ~a~ solution, which is to bind the query to the database object. This still does not seem to make full sense to me though a per the documentation a QSqlDatabase object can be associated with multiple databases through addDatabase().

It appears that I can have two different QSqlDatabase objects, each connected to different named databases. When I then create a QSqlQuery, I bind it to the database object I want to use. So the code becomes:

QSqlDatabase db;
db = QSqlDatabase::addDatabase("QSQLITE", "db");
db.setDatabaseName(directory + QDir::separator() + "db.sqlite3");
db.open();
QSqlQuery query(db);
query.exec("create table mytable (id integer)");
Kenneth Vaughn
  • 435
  • 5
  • 10