2012-07-19 41 views
12

我需要更新某個表中列中的值。我嘗試這樣做:在sqlite中更改列中的值

public void updateOneColumn(String TABLE_NAME, String Column, String rowId, String ColumnName, String newValue){ 
       String sql = "UPDATE "+TABLE_NAME +" SET " + ColumnName+ " = "+newValue+" WHERE "+Column+ " = "+rowId; 
       db.beginTransaction(); 
       SQLiteStatement stmt = db.compileStatement(sql); 
       try{ 
        stmt.execute(); 
        db.setTransactionSuccessful(); 
       }finally{ 
        db.endTransaction(); 
       } 

     } 

,我調用這個方法是這樣的:

db.updateOneColumn("roadmap", "id_roadmap",id,"sys_roadmap_status_mobile_id", "1"); 

這意味着我要設置的值1sys_roadmap_status_mobile_idid_roadmap = id.

的問題是,什麼都沒發生。我的錯誤在哪裏?

+0

首先,請閱讀了關於SQL注入攻擊! – 2012-07-19 15:10:10

+0

而且,什麼數據類型是你的列?如果他們是字符類型,你可能會想引用你的字符串。您還沒有提供'id'包含的值或任何示例數據... – 2012-07-19 15:11:13

回答

27

簡單的解決方案:

String sql = "UPDATE "+TABLE_NAME +" SET " + ColumnName+ " = '"+newValue+"' WHERE "+Column+ " = "+rowId; 

更好的解決方案:

ContentValues cv = new ContentValues(); 
cv.put(ColumnName, newValue); 
db.update(TABLE_NAME, cv, Column + "= ?", new String[] {rowId}); 
+0

我之前嘗試過此解決方案,但未在表中設置該值。 – Gabrielle 2012-07-19 15:17:25

+1

你如何驗證? – WarrenFaith 2012-07-19 15:17:56

+0

@Gabrielle看看它是否真的影響任何行。檢查受影響的行數 – 2012-07-19 15:18:07

1

下面的解決方案對我的作品更新單列值:

public long fileHasBeenDownloaded(String fileName) 
{ 
    SQLiteDatabase db = this.getWritableDatabase(); 

    long id = 0; 

    try { 
     ContentValues cv = new ContentValues(); 
     cv.put(IFD_ISDOWNLOADED, 1); 

     // The columns for the WHERE clause 
     String selection = (IFD_FILENAME + " = ?"); 

     // The values for the WHERE clause 
     String[] selectionArgs = {String.valueOf(InhalerFileDownload.fileName)}; 

     id = db.update(TABLE_INHALER_FILE_DOWNLOAD, cv, selection, selectionArgs); 
    } 
    catch (Exception e) { 
     e.printStackTrace(); 
    } 
    return id; 
}