首页 > 解决方案 > sqlite 中正确的更新语法是什么?

问题描述

我的更新语法出现了数据库 sqlite 异常。我在哪里放置引号不会收到错误“没有这样的列”?

    //2.create ContentValues to add key "column"/value
    ContentValues values = new ContentValues();
    values.put("active", _active); //update active flag

    //3.updating row
    int i = db.update(TABLE_NAME,//table
            values,//column/value
            COLUMN_UID+"="+_uid,//selections
            new String[]{String.valueOf(_uid)});//selectionargs

我的代码产生了这个错误。我知道应该在 _uid 变量周围加上引号,但这似乎也不正确。

2019-08-12 21:39:19.620 22215-22215/com.bab_c.picksandbets E/AndroidRuntime:致命异常:主进程:com.bab_c.picksandbets,PID:22215 android.database.sqlite.SQLiteException:没有这样的列: bobbyb2222 (code 1): , 编译时: UPDATE pab_pref SET active=? 哪里 uid=bobbyb2222

标签: javaandroidsqliteandroid-sqlite

解决方案


您不需要在变量周围加上引号,只需为参数使用占位符:

ContentValues values = new ContentValues();
values.put("active", _active); 
int i = db.update(TABLE_NAME, values, COLUMN_UID + " = ?", new String[]{String.valueOf(_uid)});

这是推荐的更新方式。
不要使用其他方式,例如直接传递用引号括起来的变量,因为这可能会导致sql injection


推荐阅读