0

Suppose I have an execquery statement like this:

db1.execSQL("insert into "+TABLE_NAME+" values('"name"')");

where name is a string variable which contains an apostrophe. For example:

name = "tom's database";

In this case, I get an SQLITEexception near this statement. I am certain that this is because of that single quote.

How to modify this such that the statement does not cause a crash and the name get stored in the db with the single quote intact?

I read online that every such single quote has to be prefixed by another single quote.

Can someone provide the code for the same?

SoulRayder
  • 5,072
  • 6
  • 47
  • 93

4 Answers4

3

Duplicate question. Check How to escape unsupported character in SQLite on Android?

Use

String escapedName = DatabaseUtils.sqlEscapeString(name);
db1.execSQL("insert into "+TABLE_NAME+" values('" + escapedName + "')");

See http://developer.android.com/reference/android/database/DatabaseUtils.html#sqlEscapeString%28java.lang.String%29

Community
  • 1
  • 1
Lars Blumberg
  • 19,326
  • 11
  • 90
  • 127
3

Escaping the special character in the string literal works but generally it's an error prone approach. It's better to use ? placeholder and bind arguments, like this:

db1.execSQL("INSERT INTO " + TABLE_NAME + " VALUES (?)", new String[] { name });

or use insert() with ContentValues which does essentially the same.

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

You forgot:

  1. To double the string apostrophes (since a apostrophes are the SQL string delimiters).
  2. To add the + in the INSERT string to properly add the variable.

So, I'd change the above INSERT statement to:

db1.execSQL("INSERT INTO " + TABLE_NAME + " VALUES ('" + name.replace("'", "''") + "')");
Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
2

You can use "PrepareStatement" to avoid problems

SQLiteStatement p = db1.compileStatement("insert into "+TABLE_NAME+" values(?)");
p.bindString(1, name);
p.execute();

Other form:

ContentValues values = new ContentValues();
values.put("name", name);
db1.insert(TABLE_NAME, null, values);
InnocentKiller
  • 5,234
  • 7
  • 36
  • 84
MiguelAngel_LV
  • 1,200
  • 5
  • 16