• <noscript id="e0iig"><kbd id="e0iig"></kbd></noscript>
  • <td id="e0iig"></td>
  • <option id="e0iig"></option>
  • <noscript id="e0iig"><source id="e0iig"></source></noscript>
  • QML使用Sqlite數據庫存儲ListModel數據

    標簽: qml使用Sqlite  sqlite存儲數據

    (本文為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)

    下面是官方文檔:

    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 and 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:

    KeyValue

    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"

    This data can be used by application tools.

    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 to read 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 to read 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:

    TypePropertyValueApplicability

    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

    May throw exception with code property SQLException.DATABASE_ERR, SQLException.SYNTAX_ERR, or SQLException.UNKNOWN_ERR.


    版權聲明:本文為CLinuxF原創文章,遵循 CC 4.0 BY-SA 版權協議,轉載請附上原文出處鏈接和本聲明。
    本文鏈接:https://blog.csdn.net/CLinuxF/article/details/80222318

    智能推薦

    SQlite數據庫存儲及增刪改查例子

    MainActivity: MyDatabaseHelper.class 運行截圖 例如查詢:...

    Android中的SQLite數據庫存儲

      SQLlite是一款輕量級的關系型數據庫, 作為Android系統內置的數據庫, 它的運算數度非常快,占用資源少,通常只需幾百KB的內存就足夠,SQLite不像其他關系型數據庫擁有眾多繁雜的數據類型,它的數據類型很簡單,integer 表示整型, real表示浮點型, text表示文本類型, bolb表示二進制型。  此處出示一個SQLite數據庫存儲的案例: SQLite...

    SQLite數據庫存儲(一)【安卓學習筆記】

    對于MODE_PRIVATE,MODE_APPEND兩種模式,對寫文件的影響有什么不同? MODE_PRIVATE:該文件只能被當前程序讀寫,會把原來的內容覆蓋掉 MODE_APPEND:該文件的內容可追加,不會把原來的內容覆蓋掉,新寫的內容追加在文件后面 但是對于修改文件中的部分內容,應該怎么做呢?這就需要我們用到SQLite數據庫 主要內容: 創建和打開一個SQLite 數據庫 SQLite數...

    17讀書筆記之SQLite數據庫存儲

    SQLite數據庫存儲 創建數據庫 Android管理數據庫提供了一個SQLiteOpenHelper幫助類。 借助這個類就可以簡單地對數據庫進行創建和升級。下面學習SQLiteOpenHelper的基本用法。 首先SQLiteOpenHelper是一個抽象類,我們要是用的話,需要創建一個自己的幫助類去繼承它。SQLiteOpenHelper中有兩個抽象方法。 onCreate()和onUpgra...

    【鼠】安卓學習雜記(十三)——Android數據存儲之SQLite數據庫存儲

    一、適用場景 適用于存儲一些復雜的關系型數據。 二、概述 輕量級嵌入式數據庫引擎,它支持SQL 語言,并且只利用很少的內存就有很好的性能。可存儲大量的數據。 Android SQLite對我目前的安卓學習水平而言,還是比較復雜的,在此處暫不做詳細闡述,僅以此時使用狀態闡述。 三、使用步驟 第一步:創建MyDatabaseHelper繼承SQLiteOpenHelper 第二步:在MainActiv...

    猜你喜歡

    數據庫存儲引擎

    MySQL整體架構 MySQL主要分為四層架構,分別是網絡連接層,服務層,存儲引擎層,物理層。 網絡連接層 主要負責連接管理,授權認證,安全等。每個客戶端連接都對應著服務器上的一個線程。服務器上維護一個線程池,避免為每個連接創建和銷毀線程。當客戶端連接到MySQL服務器時,服務器對其進行認證。可以通過用戶名與密碼認證,也可以通過SSL證書進行認證。登錄認證后,服務器還會驗證客戶端是否有執行某個查詢...

    數據庫存儲過程

    數據庫存儲過程 數據庫存儲過程 創建存儲過程 編寫存儲過程 數據庫存儲過程 創建存儲過程 如上圖,在需要創建存儲過程的數據庫表下面點擊函數>>新建函數,選擇過程,點擊完成,存儲過程創建成功,接下來寫存儲過程就可以了。 編寫存儲過程...

    數據庫存儲方法

    在數據庫中,有兩種數據存放方法: 1、堆:數據按照向后插入的方法,一直堆積在文件末尾,使用索引結構訪問數據時,將在索引中得到數據指針,然后獲取數據,當有數據刪除時,將其從對應位置刪除,對于頻繁更新的堆表,需要定期進行優化,使用堆表,會導致數據順序訪問原則被打破(在DBMS中做了訪問優化,性能得到部分提升),由于沒有填充因子,在相同壓縮算法下,空間能得到很大的節省,堆表很適合于順序范圍訪問,如數據倉...

    數據庫存儲引擎

    數據庫存儲引擎 服務層 第二層為服務層,它是MySQL的核心,MySQL的核心服務都在這一層,;例如查詢解析,SQL執行計劃分析,SQL執行計劃優化,查詢緩存,以及跨存儲引擎的功能都在這一層實現:存儲過程,觸發器,視圖等。現在通過下圖來觀察服務層的內部結構: 存儲引擎層 這一層負責MySQL中數據的存儲和提取。 服務器中的查詢執行引擎通過API與存儲引擎進行通信,通過接口屏蔽了不同存儲引擎之間的差...

    數據庫存儲引擎

    數據庫存儲引擎 存儲引擎的概念 案例前置知識點 MYISAM介紹 MyISAM適用的環境 InnoDB特點介紹 InnoDB適用場景 企業選擇存儲引擎的依據 修改存儲引擎 存儲引擎的概念 ·Mysql中數據用各種不同的技術存儲在文件中,每一種技術都是用不同的存儲機制、索引技巧、鎖定水平并最終提供不同的功能和能力,這些不同的技術以及配套功能在Mysql中稱為存儲引擎 ·存...

    精品国产乱码久久久久久蜜桃不卡