Reputation: 10830
So as I was learning Android, I got much advice on how to use ContentProvider
and how to insert things correctly with that using SqliteDatabase
. Now I have an error that makes no sense, at least with what everything everyone was telling me. The error is this:
android.database.sqlite.SQLiteException: near "s": syntax error:
while compiling: SELECT * FROM events WHERE time_stamp='07/21/2012 2:59:03 PM' AND
event='Test This's'
Everything works fine as long as '
doesn't appear anywhere. I know why because it needs to be escaped. But this doesn't make sense because everyone has been telling me to not use raw queries but rather use the provided bindings methods if that even made sense. Let me provide what my example is:
ContentValues newValues = new ContentValues();
newValues.put("event_id", eventId);
newValues.put("event_name", eventName);
newValues.put("start_date", startDate);
newValues.put("start_time", values.getAsString("start_time"));
newValues.put("end_date", endDate);
newValues.put("end_time", values.getAsString("end_time"));
newValues.put("location", values.getAsString("location"));
Long success = database.insert("events_info", null, newValues);
From what I have been able to understand, why should I need to escape this since its suppose to bind it!? Unless this only applies to the other methods like query()
and update()
. In either case I am hoping someone to shed some light on the proper practice in preparing Strings for SQLite insertion in Android. Thank you in advance.
Upvotes: 1
Views: 519
Reputation: 121669
SELECT * FROM events WHERE time_stamp='07/21/2012 2:59:03 PM' AND event='Test This's'
As I think you know, the date string '07/21/2012 2:59:03 PM'
is correctly delimited, and the event string 'Test This's'
isn't.
The simple fix it change the string to 'Test This''s'
The general problem, "how do you correct and validate input", is actually a VERY big question - involving many more issues than just "quote" delimiters.
Arguably your best line of defense is to use "query arguments":
EXAMPLE:
p_query = "select * from mytable where name_field = ?";
mDb.rawQuery(p_query, new String[] { uvalue });
I had a surprisingly hard time finding a good tutorial on the topic - sorry. Here's the best I could do:
Here is a good article on a related topic, "SQL Injection":
Finally, if you really want to "escape" your input string, you could do worse than use a simple Java String.replaceAll ():
Upvotes: 2