【发布时间】:2017-06-30 03:06:13
【问题描述】:
有没有一种简单的方法可以在 android 中更新 sqlite 中的表? (就像内置方法中的单行)?我有一个包含几列的表,主要是一列。我想通过主键搜索,然后更新表中的一行。
【问题讨论】:
有没有一种简单的方法可以在 android 中更新 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'");
【讨论】:
你应该得到这样的结果:
affected = db.update(TABLE_NAME, values, where, whereArgs);
UDPATE
不惜一切代价避免使用容易出错的语法进行原始查询。我在这里看到很多使用大量'"' + SOMETHING + "'" 的答案......这是非常糟糕的做法,您将花费所有时间在难以找到的地方寻找错误或完全浪费时间。
如果您必须使用原始查询,请尝试使用 String.format 形成它们以避免危险的调试会话和偏头痛。
【讨论】:
你可以像这样使用rawQuery:
cur = mDb.rawQuery("update " + TABLE_NAME
+ " set column1=mango where id='" + _id + "'",null);
在哪里
cur 是 Cursor 对象TABLE_NAME 是 NAME OF THE TABLE
_id 是 name of the column(仅示例)【讨论】:
String.format("update %s set column1=%s where id='%s'",TABLE_NAME,"mango",_id)@Waqas 答案更正确,因为它允许在不更改代码的情况下更新可变数量的字段。
那么你应该已经知道你的主键是什么了。
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
【讨论】:
试试这个:
public void updateFunction(int id) {
String updateStmnt = "UPDATE YOUR_TABLE SET YOUR_COLUMN = "
+ id;
database.execSQL(updateStmnt);
}
希望它会有所帮助。
【讨论】:
+ 字符串...它更易读且不易出错
使用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();?