2

I am having trouble with inserting a string using sqlite in an android app,
I tried,

query  = "INSERT OR REPLACE into table(_id, text) VALUES ("+data.get(i).id+", '"+data.get(i).text+"')";
MyClass.db.execSQL(query);

If my string looks like,

'I'm an android developer'

App crashes here, here is logcat result,

Caused by: android.database.sqlite.SQLiteException: near "m": syntax error: , while compiling: INSERT OR REPLACE into table (_id, text) VALUES (4, '"I'm an android developer"' )

I think it assumes that, my query ends here

'"I'

please help me to insert any case of string, either it contains single or double quotes like,

"I'm an "android" developer"
Irfan Ahmed
  • 9,136
  • 8
  • 33
  • 54

5 Answers5

5

Without any hardcoding or anything you can directly insert with using ContentValues like below..

ContentValues values = new ContentValues();
long retvalue = 0;
values.put("_id", id_here);
values.put("text", your_text_here);
retvalue = MyClass.db.insertWithOnConflict(table, null, values, CONFLICT_REPLACE);
LS_ᴅᴇᴠ
  • 10,823
  • 1
  • 23
  • 46
kalyan pvs
  • 14,486
  • 4
  • 41
  • 59
3

If you are using normal insert statement and if you have any value which contains single quote in it, then you might face a weird issue like this. So,try this..

String insert_info = "INSERT OR REPLACE INTO table(_id,text) VALUES (?,?)";
SQLiteStatement stmt = db.compileStatement(insert_info);
stmt.bindString(1, ""+data.get(i).id);
stmt.bindString(2, ""+data.get(i).text);
stmt.execute();
Hariharan
  • 24,741
  • 6
  • 50
  • 54
  • 1
    Better to use built-in [insertWithOnConflict](http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html)! – LS_ᴅᴇᴠ Dec 16 '13 at 10:51
1

Multiple options:

  1. Use ContentValues with SQLiteDatabase.insert()

  2. Use variable binding, e.g.

    db.execSQL("INSERT INTO table(_id, text) VALUES(?,?)", new String[] { idValue, textValue });
    
  3. Escape the ' in strings. The SQL way to escape it is '' and you can use DatabaseUtils helpers to do the escaping.

To escape the " in Java strings, use \".

laalto
  • 150,114
  • 66
  • 286
  • 303
0

you must replace \' with \'\' in query string:

String getQuery(){
    query  = "INSERT OR REPLACE into table(_id, text) VALUES ("+data.get(i).id+", '"+getSqlValue(data.get(i).text)+"')";
    MyClass.db.execSQL(query);
    return query;
}
String getSqlValue(String input){
    return input.replace("\'","\'\'");
}
Mohammad Asadi
  • 131
  • 2
  • 2
-3

You can use " for skipping " in a string

Viswanath Lekshmanan
  • 9,945
  • 1
  • 40
  • 64