2012-06-11 203 views
4

有沒有一種簡單的方法來更新android中的sqlite表? (像建立方法中的單行)?我有一個有幾列的表,主要是一列。我想按主鍵搜索,然後更新表中的一行。sqlite數據庫更新

回答

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(只是舉例)
+0

感謝。 :)非常感謝幫助隊友! :) – harsh

+0

通過使用string.format來構建查詢,避免使用容易出錯的語法,例如'String.format(「update%s set column1 =%s where id ='%s'」,TABLE_NAME,「mango」,_ id) 「@Waqas的答案更加準確,因爲它允許在不更改代碼的情況下更新可變數量的字段。 – Merlin

12

要使用預定義的更新使用方法在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'"); 
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

5

閱讀SQLiteDatabase.update

的文檔,你應該像這樣結束:

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

UDPATE

不惜一切代價避免使用容易出錯的語法進行原始查詢。我在這裏看到很多答案,使用了很多'"' + SOMETHING + "'" ......這是非常糟糕的做法,你會花費你所有的時間在很難找到的地方尋找錯誤,或者完全浪費時間。

如果您必須使用原始查詢,請嘗試使用String.format形成它們以避免危險的調試會話和偏移。

+0

加上一個更新。始終更喜歡使用db.update()方法,而不是手動原始查詢。試圖存儲一個包含撇號的json也會讓你信服 – kouretinho

0

試試這個:

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

希望這將有助於。

+0

考慮使用string.format而不是'+'來表示字符串......它更清晰易讀,更不容易出錯 – Merlin

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); 
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; 
}