首页 > 解决方案 > 插入多行 Qt Quick Local Storage?

问题描述

我正在 Qt Creator 中制作移动应用程序,我想使用 Qt Quick Local Storage。

我想在初始数据库创建中添加多行。

这是我的代码:

function init() {
    var db = LocalStorage.openDatabaseSync("test_db", "", "Local Storage test", 1000000)
    try {
        db.transaction(function (tx) {
            tx.executeSql('CREATE TABLE IF NOT EXISTS test (id numeric, title varchar)');

            var r = tx.executeSql('SELECT * FROM test');
            if (r.rows.length < 3) {
                tx.executeSql('INSERT INTO test VALUES (?, ?)',
                              [1, 'One'],
                              [2, 'Two'],
                              [3, 'Three']
                            );
            }
        })
    } catch (err) {
        console.log("Error creating table in database: " + err)
    };
}

问题是只插入了第一行。

如何插入多行?

这是插入初始数据的正确方法吗?

标签: sqldatabaseqtsqliteqml

解决方案


您需要单独编写执行语法。

tx.executeSql('INSERT INTO test VALUES (?, ?)',[1, 'One']);
tx.executeSql('INSERT INTO test VALUES (?, ?)',[2, 'Two']);
tx.executeSql('INSERT INTO test VALUES (?, ?)',[3, 'Three']);

或创建一个函数来插入数据。

function init() {
    var db = LocalStorage.openDatabaseSync("test_db", "", "Local Storage test", 1000000)
    try {
        db.transaction(function (tx) {
            tx.executeSql('CREATE TABLE IF NOT EXISTS test (id numeric, title varchar)');

            var r = tx.executeSql('SELECT * FROM test');
            if (r.rows.length < 3) {
                SaveData(tx,1,'One');
                SaveData(tx,2,'Two');
                SaveData(tx,3,'Three');
            }
        })
    } catch (err) {
        console.log("Error creating table in database: " + err)
    };
}


function SaveData(tx,col1, col2) {
    tx.executeSql('INSERT INTO test VALUES (?, ?)', [col1, col2]);
}

推荐阅读