SQLite, 原创, 安卓

Use SQLite UPDATE DATABASE Field Value Addition使用SQLite更新数据库实现字段值增加

Use SQLite achieve UPDATE table SET field = field + 1 WHERE id = 1;

Let’s try a normal code

SQLiteDatabase db =getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put("field", “field + 1”);
cv.put("tag", tag);
String[] args = {String.valueOf(photoId)};
return db.update(“table”, cv, "photoId=?",args);

failed,the value shows as “field + 1”, not the one we wanted.
What about use statement,Let’s try this

SQLiteDatabase db =getWritableDatabase();
db.rawQuery("UPDATE table SET field = field + 1 WHERE id = 1",null);

Gold find that the statement is not executed,search the book, and find that it only used in query ,db.rawQuery(sql).
Let’s try this

SQLiteDatabase db =getWritableDatabase();
db.execSQL("UPDATE table SET field = field + 1 WHERE id = 1");

OK, Success.
使用SQLite实现 类似 UPDATE table SET field = field + 1 WHERE id = 1;

我在使用标准的更新语句

SQLiteDatabase db =getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put("field", “field + 1”);
cv.put("tag", tag);
String[] args = {String.valueOf(photoId)};
return db.update(“table”, cv, "photoId=?",args);

实现将field字段加1时出现问题,更新后这个字段的值是 “field + 1” 而不是我需要的,后来想使用类似SQL查询的语句来实现,像这样

SQLiteDatabase db =getWritableDatabase();
db.rawQuery("UPDATE table SET field = field + 1 WHERE id = 1",null);

发现这个语句不执行,终于在试了很多次之后,想明白,这个db.rawQuery(sql)只能用于查询操作,悲剧吧~!
再换

SQLiteDatabase db =getWritableDatabase();
db.execSQL("UPDATE table SET field = field + 1 WHERE id = 1");

OK,实现了字段值增加的功能。

(894)

Related Post