在android中我使用以下语句。
model = dataHelper.rawQuery("SELECT _id, engword, lower(engword) as letter FROM word WHERE letter >= 'a' AND letter < '{' AND engword LIKE '%" + filterText + "%'", new String[ {"_id","engword", "lower(engword) as letter"});
投掷android.database.sqlite.SQLiteException: bind or column index out of range: handle 0x132330
我的代码中有什么问题?
答案 0 :(得分:40)
正确的陈述是:
model = dataHelper.rawQuery("
SELECT _id, engword, lower(engword) as letter
FROM word W
HERE letter >= 'a'
AND letter < '{'
AND engword LIKE ? ORDER BY engword ASC
",
new String[] {"%" + filterText + "%"}
);
答案 1 :(得分:22)
您提供了3个参数,但查询中没有?
。传递null而不是字符串数组作为rawQuery
的第二个参数,或者通过_id
engword
,lower(engword) as letter
和?
1)
model = dataHelper.rawQuery("SELECT ?, ?, ? FROM word WHERE letter >= 'a' AND letter < '{' AND engword LIKE '%" + filterText + "%'",new String[] {"_id","engword", "lower(engword) as letter"});
2)
model = dataHelper.rawQuery("SELECT _id, engword, lower(engword) as letter FROM word WHERE letter >= 'a' AND letter < '{' AND engword LIKE '%" + filterText + "%'", null);
修改强> 正如@Ewoks指出的那样,选项(1)是不正确的,因为预处理语句只能在WHERE子句中获取参数(?s)。
答案 2 :(得分:3)
如果有人像我一样尝试(并且失败)在getContentResolver().query
处理这个问题,我在这里管理它:
* 感谢来自@CL和@Wolfram Rittmeyer的评论,因为他们说这与rawQuery *相同
正确的方式:
public static String SELECTION_LIKE_EMP_NAME = Columns.EMPLOYEE_NAME
+ " like ?";
Cursor c = context.getContentResolver().query(contentUri,
PROJECTION, SELECTION_LIKE_EMP_NAME, new String[] { "%" + query + "%" }, null);
以前对SQL注入攻击持开放的答案:
public static String SELECTION_LIKE_EMP_NAME = Columns.EMPLOYEE_NAME
+ " like '%?%'";
String selection = SELECTION_LIKE_EMP_NAME.replace("?", query);
Cursor c = context.getContentResolver().query(contentUri,
PROJECTION, selection, null, null);