Pooshonk
Pooshonk

Reputation: 1324

How to add JS object into Sqlite database

I am having trouble trying to add a JS Object into an sqlite database. I am using cordova, creating an app for android, windows and iOS.

I have this code for my insert and retrieval...

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

The data variable is my object. When I console.log(data) before insertion i get the following

enter image description here

This my querySuccessFolderData function

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); now shows up as [Object Object]

What am I doing wrong? Do i need to convert the object again after I select it from the database? This is becoming a nightmare for me now, i've been looking at it for way too long. Any help would be much appreciated.

Upvotes: 2

Views: 2900

Answers (1)

Pooshonk
Pooshonk

Reputation: 1324

Managed to fix my issue.

Set my localStorage data.

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

Used getItem to retrieve it in another function and encoded it for the database insert

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

Then used decodedURI and jsonParse to turn it back into an object

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

Which gave me the correct data saved.

Upvotes: 1

Related Questions