Android SQLite选择参数

时间:2013-06-20 20:01:30

标签: android sqlite

我的Android应用程序中有一个SQLite数据库。我希望能够根据数据库中的YEAR列选择一个随机行。我已经能够从整个表中选择一个随机行,如下所示:

    public String[] getTEST3RandChVerScrip() {
    Cursor cursor = this.db.query("provtable Order BY RANDOM() LIMIT 1",
            new String[] { KEY_MAKE, KEY_MODEL, KEY_NOTE }, null,
            null, null, null, null);
    if (cursor != null) {
        for (cursor.moveToFirst(); !cursor.isAfterLast();) {
            String colStrings[] = new String[3];
            colStrings[0] = cursor.getString(0);
            colStrings[1] = cursor.getString(1);
            colStrings[2] = cursor.getString(2);
            return colStrings;
        }

    }
    return null;

}

但是当我尝试添加一个选择参数时,应用程序出错了。这是我添加选择参数的地方:

    public String[] getTEST3RandChVerScrip() {
    Cursor cursor = this.db.query("provtable Order BY RANDOM() LIMIT 1",
            new String[] { KEY_MAKE, KEY_MODEL, KEY_NOTE }, KEY_YEAR =  "1964",
            null, null, null, null);
    if (cursor != null) {
        for (cursor.moveToFirst(); !cursor.isAfterLast();) {
            String colStrings[] = new String[3];
            colStrings[0] = cursor.getString(0);
            colStrings[1] = cursor.getString(1);
            colStrings[2] = cursor.getString(2);
            return colStrings;
        }

    }
    return null;

}

KEY_YEAR = "1964"中的语法是否不正确?如果是这样,任何想法应该是什么?

根据tyczj的回答,我已将查询修改为:

        Cursor cursor = this.db.query("provtable Order BY RANDOM() LIMIT 1",
            new String[] { KEY_MAKE, KEY_MODEL, KEY_NOTE }, KEY_YEAR +              "=?",
            new String[] {"1964"}, null, null, null);

...我仍然收到错误消息:06-20 15:18:33.644: E/AndroidRuntime(4758): android.database.sqlite.SQLiteException: near "WHERE": syntax error: , while compiling: SELECT make, model, note FROM provtable Order BY RANDOM() LIMIT 1 WHERE year=?

2 个答案:

答案 0 :(得分:2)

您不应在表名区域

中下订单
this.db.query("provtable",
            new String[] { KEY_MAKE, KEY_MODEL, KEY_NOTE }, KEY_YEAR +              "=?",
            new String[] {"1964"}, null, null, "RANDOM() LIMIT 1");

答案 1 :(得分:1)

应该是

KEY_YEAR+"=1964"

然而,更好的语法是将您的选择设为KEY_YEAR+"=?",然后您选择的标记应为new String[] {"1964"}

也发布错误