2

Suppose I had a method like this...

long getNumItemsFromDb() {
SQLiteDatabase db = dbhelper.getReadableDatabase();
try {
    String query = "SELECT " + COL_NAME +
                    " FROM " + TABLE_NAME +
                    " WHERE " + COL_NAME + " = ?";
    String[] args = new String[] {"whatever"};
    return DatabaseUtils.longForQuery(db, query, args);
} finally {
    db.close();
}

}

...but it's possible that, for example, String COL_NAME = "select"; and String TABLE_NAME = "from"; - which is going to break the query. So, I'd obviously need to surround those values in my query String with either backticks, single quotes or double quotes - but which of these is the best practice for Android / SQLite?

NB - I have simplified my query String above to make this question simpler and more to the point. So, in reality, I do need to create the SQL manually like this rather than using one of the helper methods in Android.

NB2 - I have seen similar questions here and here but the questions/answers do not address SQLite and Android.

Community
  • 1
  • 1
ban-geoengineering
  • 18,324
  • 27
  • 171
  • 253

2 Answers2

3

I'd say go with the standard.

The ANSI standard is double quotes for quoting fields/identifiers, and that works well on SQLite.

Note that some other RDBMS's may need some help to follow the standard, but following it will allow your SQL to run unchanged on as many RDBMS's/platforms as possible.

Community
  • 1
  • 1
Joachim Isaksson
  • 176,943
  • 25
  • 281
  • 294
0

If you were to use androids class SQLitedatabase you could just simply use the query method and not worry if your selection string contains any of the identifiers.

Though when using FTS tables with MATCH identifier I noticed that you must surround the searchable string with percent signs like this: "%"+str+"%", otherwise it only matches up until a space.

Simas
  • 43,548
  • 10
  • 88
  • 116