4

有没有一种简单的方法可以在 android 中更新 sqlite 中的表?(就像内置方法中的单行)?我有一个包含几列的表,主要是一列。我想按主键搜索,然后更新表中的一行。

4

8 回答 8

13

要使用来自 android 的预定义更新方法,请按如下方式使用:

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'");
于 2012-06-11T10:16:34.280 回答
6

阅读SQLiteDatabase.update的文档

你应该得到这样的结果:

affected = db.update(TABLE_NAME, values, where, whereArgs);

UDPATE

不惜一切代价避免使用容易出错的语法进行原始查询。我在这里看到很多答案使用了很多'"' + SOMETHING + "'"......这是非常糟糕的做法,您将花费所有时间在难以找到或完全浪费时间的地方寻找错误。

如果您必须使用原始查询,请尝试使用 String.format 形成它们以避免危险的调试会话和偏头痛。

于 2012-06-11T10:20:18.037 回答
3

你可以rawQuery这样使用:

cur = mDb.rawQuery("update " + TABLE_NAME
+ " set column1=mango where id='" + _id + "'",null);

在哪里

  • curCursor对象
  • TABLE_NAMENAME OF THE TABLE
  • _idname of the column(仅示例)
于 2012-06-11T10:18:16.203 回答
1

那么你应该已经知道你的主键是什么了。

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

于 2012-06-11T10:20:02.443 回答
0

答案是:

http://www.sqlite.org/lang_update.html

SQLiteDatabase.rawQuery(...)

于 2012-06-11T10:18:01.653 回答
0

试试这个:

public void updateFunction(int id) {
            String updateStmnt  = "UPDATE  YOUR_TABLE SET YOUR_COLUMN = "
                    + id;
            database.execSQL(updateStmnt);
        }

希望它会有所帮助。

于 2012-06-11T10:20:54.360 回答
0

使用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);
于 2015-06-01T20:27:06.233 回答
0

我知道这有点老了,但万一有人需要另一种方式:

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;
}
于 2017-06-29T19:06:13.990 回答