SQL查询Android问题的条款

时间:2011-07-03 16:58:07

标签: java android sqlite

我有以下代码创建我的表。我在其中插入了看起来像这样的数据

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

Java代码:

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);
}

每当name =“TestMaxRecord”(尽管存在数据)时会抛出异常,并出现以下错误

  

android.database.sqlite.SQLiteException:没有这样的列:TestMaxRecord :,同时编译:SELECT DISTINCT _id,date,recordName,total FROM Records WHERE recordName = TestMaxRecord

我觉得它正在寻找列标题TestMaxRecord。我是一个Android新手,但几乎完全从一个例子复制了这部分(虽然它使用的是int)。在您的查询中使用int和Strings之间有区别吗?

1 个答案:

答案 0 :(得分:11)

您需要在值周围加上单引号,否则会将其视为列。

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

注意:此解决方案对Sql Injection是开放的,您应该使用参数占位符,并通过selectionArgs参数传递值:

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);
}

或者,请查看SQLiteQueryBuilder

相关问题