Qml提供了sql本地存储的解决方案,他通过openDatabaseSync() 函数提供一个能够访问SQL数据库的本地脱机存储,一般我会将这个函数封装在js funcation 内。
var db = openDatabaseSync(identifier, version, description, estimated_size, callback(db));
identifier:标识符
version:版本号
description: 数据库描述
estimated_size: 数据库初始大小
Callback(db): Currently "QSQLITE"
例如:
var db = openDatabaseSync("QDeclarativeExampleDB", "1.0", "The Example QML SQL!", 1000000);
打开执行sql数据库,生成的数据库文件默认在QDeclarativeEngine::offlineStoragePath()路径下,
同时可以有void setOfflineStoragePath ( const QString & dir )修改路径。
在实际手机应用中,S60 3rd fp2 以下部分手机不支持数据库存储,3rd fp2及5th和symbian 3所有机型已经内置了本地数据库。
import QtQuick 1.0 Rectangle { color: "white" width: 200 height: 100 Text { text: "?" anchors.horizontalCenter: parent.horizontalCenter function findGreetings() { var db = openDatabaseSync("QDeclarativeExampleDB", "1.0", "The Example QML SQL!", 1000000); db.transaction( function(tx) { // Create the database if it doesn't already exist tx.executeSql('CREATE TABLE IF NOT EXISTS Greeting(salutation TEXT, salutee TEXT)'); // Add (another) greeting row tx.executeSql('INSERT INTO Greeting VALUES(?, ?)', [ 'hello', 'world' ]); // Show all added greetings var rs = tx.executeSql('SELECT * FROM Greeting'); var r = "" for(var i = 0; i < rs.rows.length; i++) { r += rs.rows.item(i).salutation + ", " + rs.rows.item(i).salutee + "/n" } text = r } ) } Component.onCompleted: findGreetings() } }