Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problem with SQL Query Android Where Clause

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

_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 where name = "TestMaxRecord" (despite there being data in there) with the following error

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

Which looks like to me that it is looking for a column title TestMaxRecord. I am an android newbie but copied this portion pretty much exactly from an example (it was using int though). Is there a difference between using int and Strings on your query?

like image 266
easycheese Avatar asked Jul 03 '11 16:07

easycheese


1 Answers

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 the values via 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, look into SQLiteQueryBuilder

like image 120
The Scrum Meister Avatar answered Oct 13 '22 00:10

The Scrum Meister