QML使用数据库存储Model数据
2011-09-28 02:10
399 查看
(本文为utf-8格式,可以直接使用相应代码)
Models 是用来提供数据的,它既可以以 QML 的形式出现也可以是 C++的类。QML中的Model有ListModel、XmlListModel、
VisualItemModel;C++ 中的 Model 有 QAbstractItemModel、QStringList、 QList<QObject*>等。另外我们可以把数
据存到数据库里,程序启动的时候从数据库中读取数据,退出的时候把Model中的数据存放回数据库中。主要代码如下所示:
ListModel {
id: mymodel
Component.onCompleted: loadImageData()
Component.onDestruction: saveImageData()
function loadImageData() {
var db = openDatabaseSync("MyDB", "1.0", "My model SQL", 50000);
db.transaction(
function(tx) {
// Create the database if it doesn't already exist
tx.executeSql('CREATE TABLE IF NOT EXISTS Images(id INTEGER primary key, title TEXT, picture TEXT)');
var rs = tx.executeSql('SELECT * FROM Images');
var index = 0;
if (rs.rows.length > 0) {
var index = 0;
while (index < rs.rows.length) {
var myItem = rs.rows.item(index);
mymodel.append( {
"id": myItem.id,
"title": myItem.title ,
"picture": myItem.picture });
index++;
}
} else {
mymodel.append( {
"id": 1,
"title": 'apple' ,
"picture": 'content/pics/apple.png' });
mymodel.append( {
"id": 2,
"title": 'Qt Quick!' ,
"picture": 'content/pics/Qt.png' });
}
}
)
}
function saveImageData() {
var db = openDatabaseSync("MyDB", "1.0", "My model SQL", 50000);
db.transaction(
function(tx) {
tx.executeSql('DROP TABLE Images');
tx.executeSql('CREATE TABLE IF NOT EXISTS Images(id INTEGER primary key, title TEXT, picture TEXT)');
var index = 0;
while (index < mymodel.count) {
var myItem = mymodel.get(index);
tx.executeSql('INSERT INTO Images VALUES(?,?,?)', [myItem.id, myItem.title, myItem.picture]);
index++;
}
}
)
}
}
动态添加数据是非常简单的,比如我们在 onClicked 事件中可以这样做:
onClicked: mymodel.append( { "title": 'Qt', "picture": 'content/pics/Qt.png' })
删除数据:
onClicked: mymodel.remove(listView.currentIndex)
下面是官方文档:
The openDatabaseSync() and related functions provide the ability to access local offline storage in an SQL database.
These databases are user-specific and QML-specific, but accessible to all QML applications. They are stored in the Databases subdirectory ofQDeclarativeEngine::offlineStoragePath(),
currently as SQLite databases.
The API can be used from JavaScript functions in your QML:
The API conforms to the Synchronous API of the HTML5 Web Database API, W3C Working
Draft 29 October 2009.
The SQL Local Storage example demonstrates the basics of using the Offline Storage API.
the function callback is called with the database as a parameter.
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:
This data can be used by application tools.
If the current version of db is not 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.
read and modify the database.
If the callback throws exceptions, the transaction is rolled back.
read the database (with SELECT statements).
It returns a results object, with the following properties:
May throw exception with code property SQLException.DATABASE_ERR, SQLException.SYNTAX_ERR, or SQLException.UNKNOWN_ERR.
Models 是用来提供数据的,它既可以以 QML 的形式出现也可以是 C++的类。QML中的Model有ListModel、XmlListModel、
VisualItemModel;C++ 中的 Model 有 QAbstractItemModel、QStringList、 QList<QObject*>等。另外我们可以把数
据存到数据库里,程序启动的时候从数据库中读取数据,退出的时候把Model中的数据存放回数据库中。主要代码如下所示:
ListModel {
id: mymodel
Component.onCompleted: loadImageData()
Component.onDestruction: saveImageData()
function loadImageData() {
var db = openDatabaseSync("MyDB", "1.0", "My model SQL", 50000);
db.transaction(
function(tx) {
// Create the database if it doesn't already exist
tx.executeSql('CREATE TABLE IF NOT EXISTS Images(id INTEGER primary key, title TEXT, picture TEXT)');
var rs = tx.executeSql('SELECT * FROM Images');
var index = 0;
if (rs.rows.length > 0) {
var index = 0;
while (index < rs.rows.length) {
var myItem = rs.rows.item(index);
mymodel.append( {
"id": myItem.id,
"title": myItem.title ,
"picture": myItem.picture });
index++;
}
} else {
mymodel.append( {
"id": 1,
"title": 'apple' ,
"picture": 'content/pics/apple.png' });
mymodel.append( {
"id": 2,
"title": 'Qt Quick!' ,
"picture": 'content/pics/Qt.png' });
}
}
)
}
function saveImageData() {
var db = openDatabaseSync("MyDB", "1.0", "My model SQL", 50000);
db.transaction(
function(tx) {
tx.executeSql('DROP TABLE Images');
tx.executeSql('CREATE TABLE IF NOT EXISTS Images(id INTEGER primary key, title TEXT, picture TEXT)');
var index = 0;
while (index < mymodel.count) {
var myItem = mymodel.get(index);
tx.executeSql('INSERT INTO Images VALUES(?,?,?)', [myItem.id, myItem.title, myItem.picture]);
index++;
}
}
)
}
}
动态添加数据是非常简单的,比如我们在 onClicked 事件中可以这样做:
onClicked: mymodel.append( { "title": 'Qt', "picture": 'content/pics/Qt.png' })
删除数据:
onClicked: mymodel.remove(listView.currentIndex)
下面是官方文档:
Offline Storage API
Database API
The openDatabaseSync() and related functions provide the ability to access local offline storage in an SQL database.These databases are user-specific and QML-specific, but accessible to all QML applications. They are stored in the Databases subdirectory ofQDeclarativeEngine::offlineStoragePath(),
currently as SQLite databases.
The API can be used from JavaScript functions in your QML:
import Qt 4.7 Text { text: "?" 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 Local Storage example demonstrates the basics of using the Offline Storage API.
db = openDatabaseSync(identifier, version, description, estimated_size, callback(db))
Returns the database identified by identifier. If the database does not already exist, it is created with the properties description and estimated_size andthe function callback is called with the database as a parameter.
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 | Value |
---|---|
Name | The name of the database passed to openDatabase() |
Version | The version of the database passed to openDatabase() |
Description | The description of the database passed to openDatabase() |
EstimatedSize | The estimated size of the database passed to openDatabase() |
Driver | Currently "QSQLITE" |
db.changeVersion(from, to, callback(tx))
This method allows you to perform a Scheme Upgrade.If the current version of db is not 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.
db.transaction(callback(tx))
This method creates a read/write transaction and passed to callback. In this function, you can call executeSql on tx toread and modify the database.
If the callback throws exceptions, the transaction is rolled back.
db.readTransaction(callback(tx))
This method creates a read-only transaction and passed to callback. In this function, you can call executeSql on tx toread the database (with SELECT statements).
results = tx.executeSql(statement, values)
This method executes a SQL statement, binding the list of values to SQL positional parameters ("?").It returns a results object, with the following properties:
Type | Property | Value | Applicability |
---|---|---|---|
int | rows.length | The number of rows in the result | 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 | The id of the row inserted | INSERT |
相关文章推荐
- QML与C++交互:在qml中使用QSqlQueryModel显示数据库数据
- QML与C++交互:在qml中使用QSqlQueryModel显示数据库数据
- QML与C++交互:在qml中使用QSqlQueryModel显示数据库数据
- 使用QML LocalStorage来存储我们的数据
- 关于UEditor插件的使用以及UEditor数据回显问题,数据库存储标签代码前台页面如何解析问题小结
- 使用phpexcel解析Excel数据表并存储到数据库中全过程_PHP_thinkphp_cmf
- TuShare(2):使用TuShare,抓取股票数据并存储到数据库
- Android数据库(SQLite)框架(4)——使用LitePal存储数据
- python django中使用sqlite3数据库 存储二进制数据ByteArray
- 使用Java来处理C++存储在数据库中的Blob数据。
- scrapyl使用pymysql操作数据库存储数据(存入多个表)
- 安卓数据存储-使用LitePal操作数据库
- 安卓开发使用Sqllite数据库动态存储数据
- 数据库操作_连接SQL Server数据库示例;连接ACCESS数据库;连接到 Oracle 数据库示例;SqlCommand 执行SQL命令示例;SqlDataReader 读取数据示例;使用DataAdapter填充数据到DataSet;使用DataTable存储数据库表;将数据库数据填充到 XML 文件;10 使用带输入参数的存储过程;11 使用带输入、输出参数的存储过程示;12 获得数据库中表的数目和名称;13 保存图片到SQL Server数据库示例;14 获得插入记录标识号;Exce
- scrapyl使用mysqldb操作数据库存储数据(存入多个表)
- ORMLite 使用(网络数据存储到数据库)
- Android在不使用数据库的情况下存储数据的方法
- 使用dbutils工具向数据库中存储大数据
- 数据存储(4):Android数据库的操作,SQLiteOpenHelper类的使用
- Android之数据存储----使用LoaderManager异步加载数据库