简体   繁体   中英

Change a value in a column in sqlite

I need to update a value in a column from a certain table. I tried this :

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

        }

and I call this method like this :

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

which means that I want to set the value 1 in the column sys_roadmap_status_mobile_id when id_roadmap = id.

The problem is that nothing happens. Where is my mistake?

Easy solution:

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

Better solution:

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

The below solution works for me for updating single row values:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM