2

If I have a javascipt object:

 var person = new Object();
 person.name = "newPerson";
 person.occupation = "Programmer";
 person.stateName = function(){
 console.log(this.name);
};

Using the SQLite based Titanium.Database API, how can I store this object in a single field? The below is working fine:

var db = Titanium.Database.openFile(Titanium.Filesystem.getFile(
Titanium.Filesystem.getApplicationDataDirectory(),'myDatabase.db'));   
db.execute("CREATE TABLE IF NOT EXISTS myTable (persons TEXT)");

I want to then store the object in a table field:

db.execute("INSERT INTO myTable (persons) VALUES(?)", JSON.stringify(person));

But the below is returned:

SQL Statement invalid or database missing
[21:55:35:300] [Titanium.Database.DB] [Error] Exception executing: INSERT INTO myTable
(person) VALUES(?), Error was: SQL Statement invalid or database missing

1 Answer 1

1

Your sql is wrong. You have to do two things:

  1. Escape your "s in the stringified json.

  2. Enclose that string in quotes in your SQL statement.

What you are doing is the equivalent of:

db.execute("INSERT INTO myTable (persons) VALUES({name: "newPerson, stateName: function() {console.log(this.name)})");

Even simpler: INSERT INTO myTable (persons) VALUES( {name:"Joe"} );

The name part may or may not be in quotes, depends on where you do this. (Better to add them, to make your stored object a true JSON.)

What you want to do is INSERT INTO myTable(persons) VALUES ( "{\"name\": \"Joe\"} " );

Note that you had VALUES(something) without quotes and you need VALUES("something") with quotes. Also you have to escape any quotes in your something (and do other stuff, but that's another topic.)

So your statement should look more like this:

INSERT INTO myTable(persons) VALUES("{\"name\":\"newPerson\", \"stateName\": function stateName(){console.log(this.name)}}");
Sign up to request clarification or add additional context in comments.

9 Comments

As I'm sure you can tell, I'm completely new to SQLite. Could you give me an example? Thank u
even with that, it still will not work... you cannot successfully serialize the function and make this work
Also, as the comment from @AaronSaunders says, you might also think on how will you deserialize this JSON once you get it out of the database. So you might want to either rethink the object or something, but again, that is another question.
Thanks a million, this has bn very helpful. Any ideas ir links on how to deserialize?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.