PDA

View Full Version : Accessing sql local storage from C++?



Koying
18th March 2011, 01:51
Hi,

I'd like to be able to manipulate SQL databases created with openDatabaseSync in a C++ component.
The goal is to use a database filled in a C++ component as a model for QML views

Would passing the db connection created in javascript to a QObject as a property work?

danielbchapman
27th February 2014, 21:49
There wasn't a great answer and this came up on a lot of searches so I'm responding 3 years after the fact in-case someone else comes looking.

(I'm using Qt 5.2 with LocalStorage 2.0)


I just used an external variable to store the root:

QtQuick2ApplicationViewer viewer;
viewer.setMainQmlFile(QStringLiteral("qml/LightAssistant/main.qml"));
viewer.showExpanded();
LA::OFFLINE_STORAGE_PATH = viewer.engine()->offlineStoragePath();
return app.exec();


You can then iterate over the databases in the folder:
OFFLINE_PATH/Databases/$hash$.ini

(something like this) --I'm using QString dbPath;


for(int i = 0; i < list.size() && !endLoop; i++)
{
QFileInfo file = list.at(i);
if(file.fileName().endsWith(".ini"))
{
QFile ini(file.absoluteFilePath());
if (!ini.open(QIODevice::ReadOnly | QIODevice::Text))
continue;

while(!ini.atEnd())
{
QString line = ini.readLine();
if(line.contains("myDbName")) //probably could be better
{
dbPath= file.absoluteFilePath().replace(".ini", ".sqlite");
endLoop = true;
}
}

ini.close();
}

}

Look for the "name=databaseName" in each ini and then you can pass it to the local SQLITE connection which is as simple as:


QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
db.setDatabaseName(dbPath);