使用 ContentValues 和更新方法更新 sql 数据库 [英] update sql database with ContentValues and the update-method

查看:173
本文介绍了使用 ContentValues 和更新方法更新 sql 数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用 android 的 SQLiteDatabase 类的本机更新方法更新我的 SQL lite 数据库.

I would like to update my SQL lite database with the native update-method of the SQLiteDatabase class of android.

ContentValues dataToInsert = new ContentValues();                          
dataToInsert.put("name", "flo");
dataToInsert.put("location", "flotown");
String where = "id" + "=" + id;
try{    
    db.update(DATABASE_TABLE, dataToInsert, where, null);
}
catch (Exception e){
    String error =  e.getMessage().toString();
}

但我收到以下错误:

android.database.sqlite.SQLiteException: near "15": 语法错误: ,编译时:UPDATE mytable SET location=?, name=?在哪里id=2010-09-21 15:05:36.995

android.database.sqlite.SQLiteException: near "15": syntax error: , while compiling: UPDATE mytable SET location=?, name=? WHERE id=2010-09-21 15:05:36.995

我不知道应该是什么问题.不知何故,这些值没有到达 SQL 语句中.我对插入方法做了几乎相同的事情,而且效果很好.

I don´t know what should be the problem. Somehow the values do not arrive in the SQL statement. I did nearly the same with the insert method and that worked quite fine.

推荐答案

您使用的更新功能有误.应该是这样的:

You're using the update function wrong. It should be like this:

String where = "id=?";
String[] whereArgs = new String[] {String.valueOf(id)};

db.update(DATABASE_TABLE, dataToInsert, where, whereArgs);

whereArgs 数组中的字符串被替换为每个 '?'在 where 变量中.

The Strings in the whereArgs array gets substituted in for each '?' in the where variable.

即.如果你有 where = "name=? AND type=? 那么第一个 '?'将被 whereArgs[0] 替换,第二个被 whereArgs[1] 替换.

ie. if you had where = "name=? AND type=? then the first '?' would get replaced by whereArgs[0] and the second by whereArgs[1].

这篇关于使用 ContentValues 和更新方法更新 sql 数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆