Android Sqlite 选择 args[] 与 int 值 [英] Android Sqlite selection args[] with int values
问题描述
在我的 DBHelper 的 getEvents 方法中有这行代码.
Have this line of code in the getEvents method of my DBHelper.
int year, month, day;
String[] columns = new String[] { KEY_EVENTNAME, KEY_DESCRIPTION,
KEY_HOUR, KEY_MINUTE, KEY_DAY, KEY_MONTH, KEY_YEAR,
KEY_REMINDER };
Cursor c = database.query(DATABASE_TABLE, columns,
KEY_YEAR + "=?"+ " AND " + KEY_MONTH + "=?" + " AND "+ KEY_DAY + "=?",
new String[] {String.valueOf(year), String.valueOf(month), String.valueOf(day)},
null, null, KEY_MONTH + " AND "
+ KEY_DAY);
它总是什么都不返回.当我删除以下内容时
It always returns nothing. When I remove the following
int year, month, day;
String[] columns = new String[] { KEY_EVENTNAME, KEY_DESCRIPTION,
KEY_HOUR, KEY_MINUTE, KEY_DAY, KEY_MONTH, KEY_YEAR,
KEY_REMINDER };
Cursor c = database.query(DATABASE_TABLE, columns,
KEY_YEAR + "=?",
new String[] {String.valueOf(year)},
null, null, KEY_MONTH + " AND "
+ KEY_DAY);
它运行正常.我的代码有什么问题?似乎它不接受多个值作为 where 子句.谁能帮我这个?谢谢.
it runs correctly. What's the problem with my code? It seems like it doesn't accept multiple values as where clause. Can any one help me with this? Thanks.
推荐答案
答案就在标题中:您正试图将整数值传递到查询中,但实际上得到的是字符串 值.
The answer is in the title: you are trying to pass integer values into the query, but what you actually end up with are string values.
这是 Android 数据库 API 中一个可怕的设计错误;您只能将参数用于字符串.
This is a horrible design bug in the Android database API; you can use parameters only for strings.
整数没有字符串值会存在的格式和 SQL 注入问题,因此您可以直接将数字插入到 SQL 表达式中:
Integer numbers do not have the formatting and SQL injection problems that string values would have, so you can just insert the numbers directly into the SQL expression:
Cursor c = database.query(
DATABASE_TABLE, columns,
KEY_YEAR + "=" + year + " AND " +
KEY_MONTH + "=" + month + " AND " +
KEY_DAY + "=" + day,
null, null, null,
KEY_MONTH + "," + KEY_DAY);
(而且 orderBy
语法是错误的.)
(And the orderBy
syntax was wrong.)
这篇关于Android Sqlite 选择 args[] 与 int 值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!