在安卓中,有没有一种简单的方法来更新SQLite表格?(例如一个内置方法中的单行代码)?我有一个拥有几列和主键的表格。我想通过主键搜索并更新表格中的一行。
要使用 Android 预定义的 update 方法,请按照以下方式使用:
ContentValues args = new ContentValues();
args.put("col_name", "new value");
db.update("table_name", args, String.format("%s = ?", "primary_column"),
new String[]{"primary_id"});
或者要在一行中运行,请使用以下方式(不推荐):
db.execSQL("UPDATE table_name SET col_name='new_value' WHERE
primary_column='primary_id'");
阅读SQLiteDatabase.update的文档。
你应该得到类似这样的结果:
affected = db.update(TABLE_NAME, values, where, whereArgs);
更新
尽可能避免使用易出错语法的原始查询。我看到很多答案在这里使用了大量的'"' + SOMETHING + "'"
,这是极其不好的做法,你将花费大量时间寻找难以找到或完全浪费时间的错误位置。
如果必须使用原始查询,请尝试使用String.format形成它们,以避免危险的调试会话和头痛。
rawQuery
:cur = mDb.rawQuery("update " + TABLE_NAME
+ " set column1=mango where id='" + _id + "'",null);
where
cur
是 Cursor
对象TABLE_NAME
是 表名
_id
是 列名
的示例String.format("update %s set column1=%s where id='%s'",TABLE_NAME,"mango",_id)
。@Waqas的答案更正确,因为它允许更新可变数量的字段而不需要修改代码。 - Moog那么你应该已经知道什么是你的主键。
dbHelper.getWritableDatabase();
ContentValues values = createContentValues(profileVo);
db.update(ProfileVO.TABLE_NAME, values, ProfileVO.COLUMN_ID + "=" + profile.getId(), null)
这里有一个不错的教程 http://www.vogella.com/articles/AndroidSQLite/article.html
使用 database.update
可以简单地实现如下:
ContentValues values = new ContentValues();
values.put(MySQLiteHelper.COLUMN_NAME, name);
values.put(MySQLiteHelper.COLUMN_JOB, job);
values.put(MySQLiteHelper.COLUMN_DATE_START, date_start);
database.update(MySQLiteHelper.TABLE_EMPLOYEES, values, MySQLiteHelper.COLUMN_ID+"="+id, null);
我知道这有点老了,但如果有人需要另一种方法:
public boolean updateNote(Note note) {
SQLiteDatabase db = notesDbHelper.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(NotesDbContract.NoteEntry._ID, note.getId());
contentValues.put(NotesDbContract.NoteEntry.COLUMN_NAME_TITLE, note.getTitle());
contentValues.put(NotesDbContract.NoteEntry.COLUMN_NAME_DSECRIPTION, note.getDescription());
int result = db.update(NotesDbContract.NoteEntry.TABLE_NAME,
contentValues,
NotesDbContract.NoteEntry._ID + "=?", new String[]{String.valueOf(note.getId())}
);
db.close();
return result > 0;
}
db.close();
? - CoolMind试试这个:
public void updateFunction(int id) {
String updateStmnt = "UPDATE YOUR_TABLE SET YOUR_COLUMN = "
+ id;
database.execSQL(updateStmnt);
}
希望这能有所帮助。
+
来处理字符串…它更易读,也更少出错。 - Moog