Using SQLite with Qt Using SQLite with Qt sqlite sqlite

Using SQLite with Qt


By default, Qt uses the application's default database to run queries against. That is the database that was added using the default connection name. See the Qt documentation for more information. I am not sure what you mean by the default database table, since the table to operate on is normally specified in the query itself?

To answer your question, here is an implementation for one of your methods. Note that instead of returning a bool I would return a QSqlQuery instance instead to be able to iterate over the results of a query.

QSqlQuery runQuery(const Qstring& sql){    // Implicitly uses the database that was added using QSqlDatabase::addDatabase()    // using the default connection name.    QSqlQuery query(sql);    query.exec();    return query;}

You would use this as follows:

QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");db.setHostName("localhost");db.setDatabaseName("data.db");if (!db.open()){  raise ...}QSqlQuery query = runQuery("SELECT * FROM user;");while (query.next()){  ...}

Note that it is also possible to explicitly specify for which database a query should be run by explicitly specifying the relevant QSqlDatabase instance as the second parameter for the QSqlQuery constructor:

QSqlDatabase myDb;...QSqlQuery query = QSqlQuery("SELECT * FROM user;", myDb);...