Is there a common way within Android to escape all of the characters that aren't allowed in a SQLite database? For instance, "You\'Me'". Instead of me figuring out every single character that has isn't allowed and creating a bunch or replace statements. I'm looking for something like the following.
value = SQLite.escapeString(value);
ContentValues contentValues = new ContentValues();
contentValues.put("name", value);
getContentResolver().insert(CONTENT_URI, contentValues);
//Retrieve data
Cursor cursor = getContentResolver().query(CONTENT_URI, null, "name=?", new String[]{SQLite.escapeString(value)}, null);
value = SQLite.unescapeString(cursor.getString(cursor.getColumnIndex("name"));
Is this wishful thinking or is there something out there already that solves this?
UPDATE
The code above works but in the situations where you can't use the ? operator you still need some way for escaping all of the characters. For instance:
db.execSQL("CREATE TABLE " + DATABASE_TABLE + " ("
+ KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ KEY_CATEGORY + " TEXT DEFAULT Misc.);");
The . in this example will throw an exception along with several other characters. Is there a common method/way to escape all of these characters?
In SQL, strings are delimited with 'single quotes'. To use one inside a string, you have to double it.
There are no other characters that need to be escaped in SQL. (If you're embedding strings in another language, such as Java, you also have to use the escape mechanisms of that language.)
To avoid string formatting problems, you should use parameters instead:
String name = "me";
db.rawQuery("SELECT ... WHERE name = ?", new String[]{ name });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With