问题描述
我有以下的code创建我的表。我将数据插入到它,看起来像这样
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:
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);
}
据每次抛出一个异常,其中name =TestMaxRecord(尽管那里是在那里的数据),出现以下错误
It throws an exception every time where name = "TestMaxRecord" (despite there being data in there) with the following error
android.database.sqlite.SQLiteException:没有这样的列:TestMaxRecord:在编制:SELECT DISTINCT _id,日期,recordName,共有来自记录中,其中recordName = TestMaxRecord
看起来像是对我说,它正在寻找一个列标题 TestMaxRecord
。我是一个Android新手,但(这是虽然使用INT)复制这部分pretty的多少完全由一个例子。是否有使用int和字符串您的查询之间的差异?
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?
推荐答案
您需要把单引号围绕价值,否则就会把它当作一列。
You need to put single quotes around the value, otherwise it will treat it as a column.
KEY_RECORD_NAME + " = '" + name + "'"
注:该解决方案是开放的SQL注入,你应该使用参数占位符,并通过 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);
}
另外,考虑<$c$c>SQLiteQueryBuilder$c$c>
这篇关于使用SQL查询的Android Where子句问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!