android - SQLite 查询构建中的错误

标签 android android-sqlite

在我的代码中,我尝试从数据库中提取数据,但是 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/

相关文章:

android - Face API 属性 Emotion 给出 Null 对象错误

java - android-market 检索空结果

java - Android - 何时使用共享首选项以及何时使用 SQLite

android - 当我从应用程序中清除数据时删除了 Sqlite 数据库

android - 在表名中插入特殊字符

android - 如何使表头行不动?

android - 在 Android 上使用背景

java - 如何在2个不同的java文件中使用getter和setter方法

android - 自定义ListView只显示一条记录

android - 在android中创建数据库文件