PDA

View Full Version : multiple in memory sqlite databases with Qt



RolandHughes
23rd May 2013, 22:33
What is the CORRECT syntax for opening multiple SQLite In Memory databases with Qt? The example found here:

http://www.sqlite.org/inmemorydb.html

rc = sqlite3_open("file:memdb1?mode=memory&cache=shared", &db);

for a name string does not work.

Thanks,
Roland

ChrisW67
23rd May 2013, 23:55
You do it exactly the same way you handle multiple database connections to other databases.


#include <QCoreApplication>
#include <QSqlDatabase>
#include <QSqlQuery>
#include <QStringList>
#include <QDebug>

int main(int argc, char **argv)
{
QCoreApplication app(argc, argv);

QSqlDatabase db1 = QSqlDatabase::addDatabase("QSQLITE", "conn1");
db1.setDatabaseName(":memory:");
if (db1.open()) {
qDebug() << "db1 open";
QSqlQuery qry("CREATE TABLE test1 (a integer)", db1);
qDebug() << "Tables in db1" << db1.tables();
}

QSqlDatabase db2 = QSqlDatabase::addDatabase("QSQLITE", "conn2");
db2.setDatabaseName(":memory:");
if (db2.open()) {
qDebug() << "db2 open";
QSqlQuery qry("CREATE TABLE test2 (a integer)", db2);
qDebug() << "Tables in db2" << db2.tables();
}


return 0;
}

RolandHughes
24th May 2013, 12:57
I will try it, but according to the SQLite link I posted :memory: only opens a single database, i.e. the second request is going to open the SAME database on a different connection. I need to open multiple memory databases on different connections. Each database has completely different content.

ChrisW67
24th May 2013, 23:46
I you bothered to run my example code you would find that they are two, independent in-memory databases with different tables. This is exactly as described in the Sqlite page you linked:


Every :memory: database is distinct from every other. So, opening two database connections each with the filename ":memory:" will create two independent in-memory databases.