Monday, March 5, 2012

Escaping single quotes when using SQLite in Android

A verycommon problem while using sqlite and content providers are single quotes in arguements of query. Eventhough  we are not bothered about the same, it may lead to some problems  while executing the query. A simple approach to solve this issue is to use  content values and  selectionArgs.   Some examples are given below.


String sql = "select COUNT(*) FROM  table name WHERE parameter=?"; // parameter - column name
 mDB.rawQuery(sql , new String[]{param value} );

ContentValues values = new ContentValues();
values.put("categoryId", category.getCategoryId());
mDB.insert(table name , "NULL", values);


ContentValues values = new ContentValues();
values.put("registeredDate", regDate);
mDB.update(table name, values, "postId=?", new String[]{postId});

No comments:

Post a Comment