Cordova SQLite 类 - 无法从数据库返回值



所以,我正在使用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 方法中记录时,它会记录数据库中的数据。

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

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

 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;
     };
 });

最新更新