【问题标题】:how do i SELECT then parse SQLite row values to assign as variables using Cordova-sqlite-storage plugin我如何选择然后解析 SQLite 行值以使用 Cordova-sqlite-storage 插件分配为变量
【发布时间】:2017-09-24 12:53:20
【问题描述】:

我在 Cordova 有一个使用(目前仅限本地)SQLite 数据库的多页应用程序。我最初想做的就是使用单行来存储 2 个不同的值,我想偶尔选择、修改,然后再次更新该行。我想我可以选择特定的一行,但我不知道如何解析行中准备分配给变量的两个值。

我正在使用cordova-sqlite-storage 插件。

var myDB;

/first create/open the database
myDB = window.sqlitePlugin.openDatabase({ name: "mySQLite.db", location: 'default' });

//create table and populate
myDB.transaction(function (tx) {
    tx.executeSql('CREATE TABLE IF NOT EXISTS mcappDB (id text primary key, val1 integer, val2 integer)');
    tx.executeSql('INSERT INTO mcappDB VALUES (?,?,?)', ['SessionNums', 12, 15]);
}, function (error) {
    alert('Transaction ERROR: ' + error.message);
}, function () {
    alert('Table created and populated');
});

//SELECT row and parse (and needing to store parsed data as global variables)
myDB.transaction(function (tx) {
    tx.executeSql('SELECT * FROM mcappDB WHERE id="SessionNums"', [],
    function (tx, rs) {
        alert('Whats in here? ' + rs);
    },
    function (tx, error) {
        alert('select ERROR: ' + error.message);
    });
});

目前,rs 只是返回为[object Object],我无法解析它。我尝试使用rs.toString(0)rs.getString(0)rs.column.item(1)rs(1) 等均无济于事。

我实际上是从WHERE id=SessionNums 开始的,即行ID 上没有引号,但奇怪的是这返回了no such columns: SessionNums 的错误,尽管我认为使用WHERE id= 命令是为了获取行信息?!例如http://zetcode.com/db/sqlite/select/

任何和所有的帮助将不胜感激。 干杯,克里斯。

【问题讨论】:

    标签: javascript ios sqlite cordova cordova-plugins


    【解决方案1】:

    首先,确保在使用 promise 读取记录之前已插入记录。

    将插入函数和读取函数分开,然后使用这个:

    $.when(insertFunc()).done(readFunc());
    

    之后你可以解析结果如下:

    if (rs.rows.length > 0) {
        for (var i = 0; i < rs.rows.length; i++) {
           console.log("val1: " + rs.rows.item(i).val1 + "\n" + "val2: " + rs.rows.item(i).val2);
        }
    }
    

    最好的问候, @BernaAsis

    【讨论】:

      猜你喜欢
      • 2021-03-15
      • 2014-11-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-27
      • 1970-01-01
      相关资源
      最近更新 更多