如何将JS对象添加到Sqlite数据库中

时间:2014-08-22 08:40:35

标签: javascript json sqlite cordova

我在尝试将JS对象添加到sqlite数据库时遇到了麻烦。我正在使用cordova,为Android,Windows和iOS创建一个应用程序。

我有这个代码用于插入和检索...

var data = localStorage.getItem('folderData');
console.log(data);
var username = localStorage.getItem("username");
var session = localStorage.getItem("session_ID");
tx.executeSql('CREATE TABLE IF NOT EXISTS folderData (id integer primary key autoincrement, username, sessionID, folderData text)');
tx.executeSql('SELECT * FROM folderData WHERE username = "'+username+'"', [], function(tx, result) {
    if(result.rows.length > 0){
        tx.executeSql('UPDATE folderData SET folderData = "'+data+'", sessionID = "'+session+'" WHERE username = "'+username+'"');
        alert('An update has occured folderData');
    } else {
        tx.executeSql('INSERT INTO folderData (username, sessionID, folderData) VALUES ("'+username+'", "'+session+'", "'+data+'")');
        alert('An insert has occured folderData');
    }
});
tx.executeSql('SELECT folderData FROM folderData WHERE username = "'+username+'" AND sessionID = "'+session+'" ORDER BY id desc LIMIT 1', [], function(tx, result) {
    querySuccessFolderData(tx, result);
});

数据变量是我的对象。当我在插入之前控制日志(数据)时,我得到以下内容

enter image description here

这是我的querySuccessFolderData功能

function querySuccessFolderData(tx, results) {
    var len = results.rows.length;
    //alert("folderData table: " + len + " rows found.");
    var newFolderData = jsonParse(results.rows.item(0).folderData);
    for(i=0;i<len;i++)
    {
        var newFolderData = results.rows.item(i).folderData;
    }
    console.log(newFolderData);
}

console.log(newFolderData);现在显示为[Object Object]

我做错了什么?从数据库中选择对象后,是否需要再次转换对象?这对我来说现在变成了一场噩梦,我一直在看它太久了。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:1)

管理以解决我的问题。

设置我的localStorage数据。

localStorage.setItem("folderData", JSON.stringify(data['root']));

使用getItem在另一个函数中检索它并将其编码为数据库插入

var data = localStorage.getItem('folderData');
data = encodeURI(data);

然后使用decodeURI和jsonParse将其变回对象

var newFolderData = results.rows.item(0).folderData;
newFolderData = decodeURI(newFolderData);
newFolderData = jsonParse(newFolderData);

这让我保存了正确的数据。