【问题标题】:Cordova SQLite class - cannot return value from databaseCordova SQLite 类 - 无法从数据库返回值
【发布时间】:2017-03-28 15:17:16
【问题描述】:

所以,我正在使用 Cordova 和 SQLite 构建一个应用程序,下面是我创建的用于处理数据库属性和方法的对象存储。

function Storage(connection, platform)
{
    if (platform == 'mobile') {
        this.db = window.sqlitePlugin.openDatabase({name: connection.name, location: connection.location});
    } else if (platform == 'web') {
        this.db = window.openDatabase(connection.name, connection.version, connection.mode, -1);
    }

    this.read = function(sql, vals) {
        var rows = null;

        this.db.transaction(function(tx) {
            tx.executeSql(sql, vals, function(tx, res) {
                rows = res.rows;
            });
        }, function(error) {
            console.log('Transaction error: '+error.message);
        });

        return rows;
    };
};

var connection = {
    name: 'database.db',
    version: '1.0',
    mode: 'Development'
};

var db = new Storage(connection, 'web');

var sql = '';
sql += 'SELECT *';
sql += ' FROM countdown';
sql += ' WHERE countdown_status != ?;';
var rows = db.read(sql, [1]);
console.log(rows);

这段代码记录了“null”,我不知道为什么,因为我的数据库中有数据。当我尝试从 tx.executeSql 方法中记录时,它会记录数据库中的数据。

关于为什么我无法从该函数中获取这些数据的任何想法? 非常感谢。

【问题讨论】:

    标签: sqlite cordova


    【解决方案1】:

    数据库读取是异步的 - 它需要将数据返回到回调函数,如下所示:

     getHighScore: function (type,callback) {
    
      var query = "SELECT Value FROM HighScore where Type = '" + type + "';";
    
    playedDb.transaction(function (tx) {
    
     tx.executeSql(query, [], function (tx, res) {
         var out;
    
         if (typeof res.rows.item(0) === "undefined") {
             if (typeof callback === "function") {
               callback(-1);
               return;
             };
         } else {
             out = res.rows.item(0).Value
    
             //task 301 only allow alphanumeric and decimal point (for version)
             out = String(out).replace(/[^0-9a-z\.]/gi, '');
    
             if (typeof callback === "function") {
                callback(out);
                return;
             };
         }
    
     }, function (e) {
         console.log("getHighScore FAILED: " + e.message);
         if (typeof callback === "function") {
             callback(-2);
             return;
         };
     });
    

    【讨论】:

      猜你喜欢
      • 2020-04-23
      • 2018-01-14
      • 2020-04-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-07-13
      • 2017-08-01
      相关资源
      最近更新 更多