Problem with SQL Query Android Where clause

I have the following code that creates my table. I insert data into it that look like

_id date recordName total -------------------------------------- 7 2011 TestMaxRecord 5 

Java Code:

 public static final String KEY_ROWID = "_id"; public static final String KEY_DATE = "date"; public static final String KEY_TOTAL = "total"; public static final String KEY_RECORD_NAME = "recordName"; private static final String DATABASE_CREATE_RECORDS = "create table " + DATABASE_TABLE_RECORDS + " (" + KEY_ROWID + " integer primary key autoincrement, " + KEY_DATE + " text not null, " + KEY_RECORD_NAME + " text not null, " + KEY_TOTAL + " text not null);"; public Cursor getRecord(String name) throws SQLException { return mDb.query(true, DATABASE_TABLE_RECORDS, new String[] {KEY_ROWID, KEY_DATE, KEY_RECORD_NAME, KEY_TOTAL}, KEY_RECORD_NAME + " = " + name, null, null, null, null, null); } 

It throws an exception every time name = "TestMaxRecord" (despite the presence of data there) with the following error

android.database.sqlite.SQLiteException: no such column: TestMaxRecord: at compilation: SELECT DISTINCT _id, date, recordName, total FROM Records WHERE recordName = TestMaxRecord

It seems to me that it is looking for the column heading of TestMaxRecord . I'm new to Android, but I copied this part almost exactly from the example (he used int though). Is there any difference between using int and strings in your request?

+6
source share
1 answer

You need to put single quotes around the value, otherwise it will treat it as a column.

 KEY_RECORD_NAME + " = '" + name + "'" 

Note. This solution is open to Sql Injection, you should use parameter placeholders and pass values ​​through the selectionArgs argument:

 public Cursor getRecord(String name) throws SQLException { return mDb.query(true, DATABASE_TABLE_RECORDS, new String[] {KEY_ROWID, KEY_DATE, KEY_RECORD_NAME, KEY_TOTAL}, KEY_RECORD_NAME + " = ?", new String[] {name}, null, null, null, null); } 

Alternatively consider SQLiteQueryBuilder

+11
source

Source: https://habr.com/ru/post/891914/


All Articles