0

我不确定自己做错了什么,但我正在尝试将表列中的单个整数值从 0 更新为 1。创建数据库时,我使用以下方法将列的所有值设置为零:

for (int i = 0; i < setups.length; i++) {
        ContentValues values = new ContentValues();
        values.put(JokeDbContract.TblJoke.COLUMN_NAME_SETUP, setups[i]);
        values.put(JokeDbContract.TblJoke.COLUMN_NAME_PUNCHLINE, punchlines[i]);
        values.put(JokeDbContract.TblJoke.COLUMN_NAME_USED, 0);

        db.insert(JokeDbContract.TblJoke.TABLE_NAME, null, values);
    }

然后,在实际活动中,我正在做:

private void findNewJoke() {
    JokeDb jokeDb = JokeDb.getInstance(this);
    SQLiteDatabase theDb = jokeDb.getDB();
    String selection = JokeDbContract.TblJoke.COLUMN_NAME_USED + "=" + 0;

    // Query database for a joke that has not been used, update the fields
    // theJoke and thePunchline appropriately
    String[] columns = {JokeDbContract.TblJoke._ID,
                        JokeDbContract.TblJoke.COLUMN_NAME_PUNCHLINE,
                        JokeDbContract.TblJoke.COLUMN_NAME_SETUP,
                        JokeDbContract.TblJoke.COLUMN_NAME_USED};

    Cursor c = theDb.query(JokeDbContract.TblJoke.TABLE_NAME, columns, selection,
                        null, null, null, null);

    if (c.moveToFirst() == false) {
        Toast.makeText(this, R.string.error_retrieving_joke, Toast.LENGTH_LONG).show();
        Log.e(getString(R.string.app_name),"No jokes retreived from DB in JokeActivity.findNewJoke()!");
    }
    else {
        ContentValues values = new ContentValues();
        theSetup = c.getString(c.getColumnIndexOrThrow(JokeDbContract.TblJoke.COLUMN_NAME_SETUP));
        thePunchline = c.getString(c.getColumnIndexOrThrow(JokeDbContract.TblJoke.COLUMN_NAME_PUNCHLINE));

        String updateSelection = JokeDbContract.TblJoke.COLUMN_NAME_SETUP + "=" + theSetup;

        values.put(JokeDbContract.TblJoke.COLUMN_NAME_USED, 1);

        theDb.update(JokeDbContract.TblJoke.TABLE_NAME, values, updateSelection, null);
    }
}

我收到更新错误:

java.lang.RuntimeException: .... while compiling: UPDATE jokes SET used=? 
WHERE setup=Why do programmers always mix up Halloween and Christmas?

似乎我没有为已使用的列设置实际值。程序最终所做的是循环播放 used=0 的笑话,然后在查看时将 used 设置为 1。所以查询只提取那些尚未使用的笑话。我有一种感觉,我错过了一些简单的东西,一个可以希望的东西。

4

1 回答 1

4

我认为您在使用引号时遇到问题。

例子:

String updateSelection = JokeDbContract.TblJoke.COLUMN_NAME_SETUP + "=\"" + theSetup + "\"";

但是,推荐的方法是:

theDb.update(JokeDbContract.TblJoke.TABLE_NAME, values, JokeDbContract.TblJoke.COLUMN_NAME_SETUP + " = ?", new String[] { theSetup });

最好使用 field = ?,因为这有助于 sqlite 缓存查询(我相信)。

于 2013-04-09T06:18:18.030 回答