Teja Nandamuri
Teja Nandamuri

Reputation: 11201

Unable to insert a formatted string into sqlite

I joined three objects using "components joined by string". The NSLog of the joinedString gives me this:

joined string  is (
"722.3300",
"4924.6700",
"225.38"
)

When I added this to an array,it appears like the following :

array objects are:

   {  
        "obj1",
        "obj2",
         "(\n    \"722.3300\",\n    \"4924.6700\",\n    \"225.38\"\n)",
         "obj4"
     }

I tried to insert these values into my sqlite

      insertString=[NSString stringWithFormat:@"INSERT INTO MY_T (field1) VALUES (\"%@\")",[array objectatIndex:0]];    //this executes perfectly

      insertString=[NSString stringWithFormat:@"INSERT INTO MY_T (field1) VALUES (\"%@\")",[array objectatIndex:1]];     //this executes perfectly

      insertString=[NSString stringWithFormat:@"INSERT INTO MY_T (field1) VALUES (\"%@\")",[array objectatIndex:2]];    //oops...somethings wrong here

      insertString=[NSString stringWithFormat:@"INSERT INTO MY_T (field1) VALUES (\"%@\")",[array objectatIndex:3]];        //this executes perfectly

IS there any other way to insert the joined string? Kindly help me in this issue.

Upvotes: 0

Views: 247

Answers (1)

Jeffery Thomas
Jeffery Thomas

Reputation: 42588

You should use single quotes (') not double quotes (") to sqlite strings.

insertString=[NSString stringWithFormat:@"INSERT INTO MY_T (field1) VALUES ('%@')",[array objectatIndex:0]];
insertString=[NSString stringWithFormat:@"INSERT INTO MY_T (field1) VALUES ('%@')",[array objectatIndex:1]];
insertString=[NSString stringWithFormat:@"INSERT INTO MY_T (field1) VALUES ('%@')",[array objectatIndex:2]];
insertString=[NSString stringWithFormat:@"INSERT INTO MY_T (field1) VALUES ('%@')",[array objectatIndex:3]];

If the string you are inserting contains a single quote, then you should escape it by using two single quotes (''). See - stringByReplacingOccurrencesOfString:withString:.

insertString=[NSString stringWithFormat:@"INSERT INTO MY_T (field1) VALUES ('%@')", [[array objectatIndex:0] stringByReplacingOccurrencesOfString:@"'" withString:@"''"]];
insertString=[NSString stringWithFormat:@"INSERT INTO MY_T (field1) VALUES ('%@')", [[array objectatIndex:1] stringByReplacingOccurrencesOfString:@"'" withString:@"''"]];
insertString=[NSString stringWithFormat:@"INSERT INTO MY_T (field1) VALUES ('%@')", [[array objectatIndex:2] stringByReplacingOccurrencesOfString:@"'" withString:@"''"]];
insertString=[NSString stringWithFormat:@"INSERT INTO MY_T (field1) VALUES ('%@')", [[array objectatIndex:3] stringByReplacingOccurrencesOfString:@"'" withString:@"''"]];

Upvotes: 1

Related Questions