这是单例类型用于读写 SQLite 数据库。
To use the types in this module, import the module and call the relevant functions using the
LocalStorage
类型:
import QtQuick.LocalStorage 2.0 import QtQuick 2.0 Item { Component.onCompleted: { var db = LocalStorage.openDatabaseSync(...) } }
These databases are user-specific and QML-specific, but accessible to all QML applications. They are stored in the
数据库
subdirectory of
QQmlEngine::offlineStoragePath
(), currently as
SQLite
数据库。
Database connections are automatically closed during Javascript garbage collection.
The API can be used from JavaScript functions in your QML:
import QtQuick 2.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() } }
The API conforms to the Synchronous API of the HTML5 Web Database API, W3C Working Draft 29 October 2009 .
The SQL 本地存储范例 演示使用离线存储 API 的基础知识。
import QtQuick.LocalStorage 2.0 as Sql db = Sql.openDatabaseSync(identifier, version, description, estimated_size, callback(db))
The above code returns the database identified by 标识符 . If the database does not already exist, it is created, and the function callback is called with the database as a parameter. 标识符 is the name of the physical file (with or without full path) containing the database. description and estimated_size are written to the INI file (described below), but are currently unused.
May throw exception with code property SQLException.DATABASE_ERR, or SQLException.VERSION_ERR.
When a database is first created, an INI file is also created specifying its characteristics:
Key | 值 |
---|---|
Identifier |
The name of the database passed to
openDatabase()
|
版本 |
The version of the database passed to
openDatabase()
|
描述 |
The description of the database passed to
openDatabase()
|
EstimatedSize |
The estimated size (in bytes) of the database passed to
openDatabase()
|
Driver | Currently "QSQLITE" |
通过应用程序工具可以使用此数据。
This method allows you to perform a Scheme Upgrade .
If the current version of db 不是 from , then an exception is thrown.
Otherwise, a database transaction is created and passed to callback . In this function, you can call executeSql on tx to upgrade the database.
May throw exception with code property SQLException.DATABASE_ERR or SQLException.UNKNOWN_ERR.
See example below.
var db = LocalStorage.openDatabaseSync("ActivityTrackDB", "", "Database tracking sports activities", 1000000); if (db.version == "0.1") { db.changeVersion("0.1", "0.2", function(tx) { tx.executeSql("INSERT INTO trip_log VALUES(?, ?, ?)", [ "01/10/2016","Sylling - Vikersund", "53" ]); } });
This method creates a read/write transaction and passed to callback . In this function, you can call executeSql on tx to read and modify the database.
If the callback throws exceptions, the transaction is rolled back. Below you will find an example of a database transaction which catches exceptions.
var db = LocalStorage.openDatabaseSync("ActivityTrackDB", "", "Database tracking sports activities", 1000000); db.transaction( try { function(tx) { tx.executeSql("INSERT INTO trip_log VALUES(?, ?, ?)", [ "01/10/2016","Sylling - Vikersund", "53" ]); } } catch (err) { console.log("Error inserting into table trip_log: " + err); } )
In the example you can see an
insert
statement where values are assigned to the fields, and the record is written into the table. That is an
insert
statement with a syntax that is usual for a relational database. It is however also possible to work with JSON objects and store them in a table.
Let's suppose a simple example where we store trips in JSON format using
date
as the unique key. An example of a table that could be used for that purpose:
create table trip_log(date text, data text)
The assignment of values to a JSON object:
var obj = {description = "Vikersund - Noresund", distance = "60"}
In that case, the data could be saved in the following way:
db.transaction(function(tx) { result = tx.executeSQL("insert into trip_log values (?,?)", ["01/11/2016", JSON.stringify(obj)]) }
This method creates a read-only transaction and passed to
callback
. In this function, you can call
executeSql
on
tx
to read the database (with
select
statements).
This method executes an SQL 语句 , binding the list of 值 to SQL positional parameters ("?").
It returns a results object, with the following properties:
类型 | 特性 | 值 | Applicability |
---|---|---|---|
int | rows.length | 结果中的行数 | SELECT |
var | rows.item(i) | Function that returns row i of the result | SELECT |
int | rowsAffected | The number of rows affected by a modification | UPDATE, DELETE |
string | insertId | 插入行的 ID | INSERT |
May throw exception with code property SQLException.DATABASE_ERR, SQLException.SYNTAX_ERR, or SQLException.UNKNOWN_ERR.
见以下范例:
// Retrieve activity date, description and distance based on minimum // distance parameter Pdistance function db_distance_select(Pdistance) { var db = LocalStorage.openDatabaseSync("ActivityTrackDB", "", "Database tracking sports activities", 1000000); db.transaction( function(tx) { var results = tx.executeSql("SELECT rowid, date, trip_desc, distance FROM trip_log where distance >= ?",[Pdistance]); for (var i = 0; i < results.rows.length; i++) { listModel.append({"id": results.rows.item(i).rowid, "date": results.rows.item(i).date, "trip_desc": results.rows.item(i).trip_desc, "distance": results.rows.item(i).distance}); } } }
object openDatabaseSync(string name, string version, string description, int estimated_size, jsobject callback(db))
Opens or creates a local storage sql database by the given parameters.
名称
is the database name
version
is the database version
description
is the database display name
estimated_size
is the database's estimated size, in bytes
callback
is an optional parameter, which is invoked if the database has not yet been created.
返回创建的数据库对象。