[SailfishDevel] Connect to 2 databases
Matthias Fehring
buschmann at huessenbergnetz.de
Wed Sep 14 21:40:50 UTC 2016
Am Donnerstag, 8. September 2016, 14:40:16 CEST schrieb Chris Walker:
> Can anybody point me in the direction of some C++ code to connect to
> two SQL databases please?
Does it have to be pure C++ code? If not and if it can be the Qt way, read on.
:)
> I want to have one set as read-only and the other as read-write.
>
> Whatever I'm doing is wrong as I always end up with a default
> connection.
Have a look at QSqlDatabase and it's addDatabase() method. [1]
Example for two SQLite databases:
You have to set a connection name for each database.
> QSqlDatabase rodb = QSqlDatabase::addDatabase(QStringLiteral("QSQLITE"),
QStringLiteral("rodb"));
> rodb.setConnectOptions(QStringLiteral("QSQLITE_OPEN_READONLY");
> rodb.setDatabaseName(QStringLiteral("/full/path/to/ro_database.sqlite"));
>
> if (rodb.open()) {
> QSqlQuery qro(rodb);
> .....
> }
>
> QSqlDatabase rwdb = QSqlDatabase::addDatabase(QStringLiteral("QSQLITE"),
QStringLiteral("rwdb"));
> rwdb.setDatabaseName(QStringLiteral("/full/path/to/rw_database.sqlite"));
> if (rwdb.open()) {
> QSqlQuery qrw(rwdb);
> .....
> }
Later on you can refer everywhere in your application to the databases by
using the connection names (rodb and rwdb):
> QSqlDatabase rodb = QSqlDatabase::database(QStringLiteral("rodb"));
> QSqlQuery q(rodb);
> ....
Best greetings
Matthias
[1] http://doc.qt.io/qt-5/qsqldatabase.html#addDatabase
--
Das Gesetz hat zum Schneckengang verdorben, was Adlerflug geworden wäre.
(Friedrich Schiller - Die Räuber)
Und der Buschfunk spielt gerade "Pikse Palve" von "In Extremo".
www.buschmann23.de
GPG-Key: 3A70A936614C3258
GPG Fingerprint: D786 DDF8 4CA9 00BC CDE0 9A5F CCC5 125D 6E87 D4FC
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 801 bytes
Desc: This is a digitally signed message part.
URL: <https://lists.sailfishos.org/pipermail/devel/attachments/20160914/c62ad388/attachment.sig>
More information about the Devel
mailing list