Debabrata
Debabrata

Reputation: 150

How To save A JSON string to One Field Of Sqlite in iOS?

Hi I have Some data in JSON format like below:

`contentJson=`[{"key1":"Value1","key2":"Value2","key3":"Value3","key4":"Value4","key5":"Value5","key6":"Value6","key7":"Value7", "key8":"Value8"},{"key1":"Value1","key2":"Value2","key3":"Value3","key4":"Value4","key5":"Value5","key6":"Value6","key7":"Value7", "key8":"Value8"}]

How can I save all Data to one Field in Sqlite Database ?

My code is

 NSString *statement = [[NSString alloc]initWithFormat:@"INSERT INTO mydatabase(contentJson,ID) VALUES(\"%@\",%d)",contentJson,ID];

But its not inserting anything.If i m inserting manually Through SQlitemanager then i m getting Error such as error at "Key1 ......

I would highly appreciate it if someone could help me out by showing me how to do this.

Upvotes: 1

Views: 3045

Answers (1)

gbtimmon
gbtimmon

Reputation: 4332

Your interporlated string would look like this :

INSERT INTO mydatabase(contentJson,ID) VALUES(
"[{"key1":"Value1","key2":"Value2","key3":"Value3","key4":"Value4",
"key5":"Value5","key6":"Value6","key7":"Value7", "key8":"Value8"},
{"key1":"Value1","key2":"Value2","key3":"Value3","key4":"Value4",
"key5":"Value5","key6":"Value6","key7":"Value7", "key8":"Value8"}]",
ID);

You need to exacpe the " in the string because it is confusing your rdbms.

Maybe try

NSString *statement = [[NSString alloc]initWithFormat:@"INSERT INTO mydatabase(contentJson,ID) VALUES('%@',%d)",contentJson,ID];

The true solution however would be to use Prepared Statements instead of SQL String in an appliaction. This is not an issue when you use prepared statements.

Upvotes: 3

Related Questions