5

我正在尝试在 javascript 中使用 sqlite 实现缓存。我有一个 json 对象,我试图将其转换为字符串并输入到数据库中,但不断收到语法错误。

该表由两个字段组成,一个 md5 字符串和一个 json 字符串,这是我定义数据库和表的方式

   db = window.openDatabase("Database", "1.0", "Cordova Demo",10485760);

    db.transaction(function(tx){
         tx.executeSql('DROP TABLE IF EXISTS CACHE_DATA');
         tx.executeSql('CREATE TABLE IF NOT EXISTS CACHE_DATA (md5 TEXT UNIQUE, data TEXT)');
    },function(tx,error){
        console.log('tx error: ' + error);
    },function(){
        console.log('tx success');
    });

这就是我尝试输入变量 d.data 是 json 对象的数据的方式。

   var jsonString = JSON.stringify(d.data, null, '');

            db.transaction(function(tx){
                tx.executeSql('INSERT OR REPLACE INTO CACHE_DATA (md5, data) VALUES ("'+hash+'", "'+jsonString+'")');
            },function(tx,error){
                console.log(JSON.stringify(tx.message));
                console.log(JSON.stringify(error));
            },function(){
                console.log('tx success');
            });

             console.log(jsonString);

哪个会抛出错误

08-27 23:19:55.702: E/SQLiteLog(29831): (1) near "networks": syntax error

我要输入的实际字符串如下所示

08-27 23:19:55.652: D/CordovaLog(29831): {"networks":[{"id":"66","name":"Test"}],"expires":1346138396}

我在想它与 json 字符串中的引号有关,但字段类型只是文本,所以我不确定语法错误可能是什么。

有任何想法吗?

4

4 回答 4

7

我发现JSON字符串在变成字符串后需要转义

            var jsonString = escape(JSON.stringify(d.data));

            db.transaction(function(tx){
                tx.executeSql('INSERT OR REPLACE INTO CACHE_DATA (md5, json, expires) VALUES ("'+hash+'", "'+jsonString+'","'+expireStamp+'")');
            },function(tx,error){
                console.log(JSON.stringify(tx.message));
                console.log(JSON.stringify(error));
            },function(){

                });
于 2012-08-28T11:13:43.063 回答
3

您是否尝试过将它们作为数组传递:

var valuesInArray = [hash, JSON.stringify(d.data, null, "");

tx.executeSql("INSERT OR REPLACE INTO CACHE_DATA (md5, data) VALUES (?, ?)", valuesInArray, function(tx, result)  {
  // Success Callback
});
于 2012-08-28T07:55:44.203 回答
1

我们也可以尝试encodeURI()decodeURI()。这是一个简单的例子:

var jsonString = encodeURI(JSON.stringify(d.data, null, ''));

        db.transaction(function(tx){
            tx.executeSql('INSERT OR REPLACE INTO CACHE_DATA (md5, data) VALUES ("'+hash+'", "'+jsonString+'")');
        },function(tx,error){
            console.log(JSON.stringify(tx.message));
            console.log(JSON.stringify(error));
        },function(){
            console.log('tx success');
        });

并用于解码

var data = JSON.parse(decodeURI(sqlData.data));

注意:escape()unescape()可能有效。但escape()函数在 JavaScript 1.5 版中已被弃用。

于 2018-02-06T10:05:14.030 回答
0

@布莱恩

第一个问题 - 是否可以将 json 对象转换为字符串并将该字符串存储到 sqlite 数据库中?

第二个问题

  • 如果 json 包含多个图像的 url。然后在在线模式下,它将从网络上获取 url 图片。但是如果我们将这些 url 存储在 sqlite 数据库中,那么是否可以在 cordova 应用程序中以离线模式显示这些图像?

如果是,那么我们将如何存储这些图像

科尔多瓦的初学者

将在线应用程序转换为离线应用程序所需的帮助。 离子角 2 应用程序

于 2017-07-22T19:35:18.933 回答