gpt4 book ai didi

android - SQLite 查询构建中的错误

转载 作者:行者123 更新时间:2023-11-29 17:53:25 25 4
gpt4 key购买 nike

在我的代码中,我尝试从数据库中提取数据,但是 SELECTARGS 不适合 QUERY 的数据类型......我这样做了:

ArrayList<String> al = new ArrayList<String>();
String selectSQL = "Select * from " + Wish_list_Table.TABLE_NAME
+ " where " + Wish_list_Table.COL_CATEGORY + "";
String[] SelectionArgs = new String[1];
SelectionArgs[0] = al.get(1);
String[] add = { "" + SelectionArgs[0] };
Log.i("select_string", "" + add.toString());

TextView textView = getGenericView();
Cursor selectdata = db.rawQuery(selectSQL, add);

最佳答案

您为查询准备了添加参数,但没有传递它:
您在查询中缺少 = ?...

String selectSQL = "Select * from " + Wish_list_Table.TABLE_NAME +
" where " + Wish_list_Table.COL_CATEGORY + " = ?";

现在,该怎么做...

一旦你的光标被填满(不要跟随这个查询,它非常特定于我的应用程序):

    final Cursor cur = db.rawQuery
(
"SELECT DISTINCT strftime('%Y', [date]) Year FROM " +
DB_TABLE + " WHERE Year > date('now', '-11 years') " +
"ORDER BY Year DESC", null
);

您可以非常轻松地提取列值:

    if (cur != null)
{
if (cur.moveToFirst())
{
tmp = new String[cur.getCount()];
do
{
tmp[cur.getPosition()] =
cur.getString(cur.getColumnIndex("Year"));
}
while (cur.moveToNext());
}
}
cur.close();

tmp是我之前定义的一个String[],需要用这个方法填充,返回一个基于数字(年份)的字符串数组(字符串形式的年份数组)

值得注意的是:

1 - check wether the Cursor is null. If so, just return something empty or null.
2 - If (hopefully) not, move to the first record and cycle till the end of the records, taking the value/s from the column/s you're interested in (normally you'd only select the columns you're interested in, because * is an overkill)

如果只返回1行,就更简单了:
只需移动到第一条记录并从您的行中提取每一列(不循环)。

并且(只是为了完整性,而不是诱导您对 SQL 命令使用 rawQuery),您可以使用 execSQL 函数(这个不是 SQL查询,而是一个SQL 命令,因为您修改了数据库)。

关于android - SQLite 查询构建中的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21351522/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com