0

it seems the SQLiteDatabase.query() method doesn't replace my ?s in the where clause with the selectionArgs:

String[] columns = new String[] { Table.COL_WEIGHT };
String[] selectionArgs = new String[] { Table.COL_DATE, Table.COL_DATE,
        Table.TABLE_NAME };

String sqlquery = SQLiteQueryBuilder.buildQueryString(false, Table.TABLE_NAME,
        columns, "?=(SELECT max(?) FROM ?)", null, null, null, null);

Cursor cursor = mDb.rawQuery(sqlquery, selectionArgs);

This thows the following exception:

FATAL EXCEPTION: main
java.lang.RuntimeException:
Unable to start activity ComponentInfo{Activity}:
android.database.sqlite.SQLiteException: near "?":
syntax error (code 1): , while compiling:
SELECT Weight FROM Bodyfat WHERE ?=(SELECT max(?) FROM ?)

While:

String sql = String.format("SELECT %s FROM %s WHERE %s=(SELECT max(%s) FROM %s)",
        Table.COL_WEIGHT, Table.TABLE_NAME, Table.COL_DATE,
        Table.COL_DATE, Table.TABLE_NAME);
//SELECT Weight FROM Bodyfat WHERE Date=(SELECT max(Date) FROM Bodyfat)


Cursor cursor = mDb.rawQuery(sql, null);

Works like expected. Am I using query() and it's selectionArgs correctly?

Kurztipp
  • 391
  • 2
  • 18
  • **"?"** doesn't work the way you are trying. You must use input parameters in your query too. – waqaslam Dec 25 '13 at 20:18
  • Could you please give an example, Waqas? – Kurztipp Dec 25 '13 at 20:23
  • Take a look at the Java tutorial: http://docs.oracle.com/javase/tutorial/jdbc/basics/prepared.html – Morrison Chang Dec 25 '13 at 20:27
  • consult the Reading module in this article http://www.androidhive.info/2011/11/android-sqlite-database-tutorial/ – waqaslam Dec 25 '13 at 20:28
  • The only difference I see in the androidhive article is that they used query() instead of rawQuery what I already tried: `Cursor cursor = mDb.query(Table.TABLE_NAME, columns, "?=(SELECT max(?) FROM ?)", selectionArgs, null, null, null);` crashes too. – Kurztipp Dec 25 '13 at 20:48
  • It seems that it really is because of passing a tablename as parameter since `Cursor cursor = mDb.query(Table.TABLE_NAME, columns, "?=(SELECT max(?) FROM " + Table.TABLE_NAME + ")", selectionArgs, null, null, null);` works. – Kurztipp Dec 26 '13 at 18:22

0 Answers0