触发多个更新时,Android SQLite数据库不会更新

时间:2013-05-05 08:48:44

标签: android sqlite sql-update

我正在尝试更新Android中的sql数据库。

public boolean updatepasswordbySimcardnumber(String simcard, String password) { 
          mDbHelper = new DatabaseHelper(mCtx);
          mDb = mDbHelper.getWritableDatabase();         
         Cursor mCursor = null;
         int retvalue = 0;

         mCursor = mDb.query(SQLITE_TABLE, new String[] {KEY_ROWID,
                   KEY_IDNUM, KEY_SIMCARD, KEY_DESCRIPTION, KEY_MODEL, KEY_TIMEINSTANCE, KEY_PASSWORD}, 
                   null, null, null, null, null);

         for(mCursor.moveToFirst(); !mCursor.isAfterLast(); mCursor.moveToNext()){
             if(mCursor.getString(2).equals(simcard)){
                   ContentValues updatevalue = new ContentValues();          
                   updatevalue.put(KEY_PASSWORD, password);             
                   long colId = mCursor.getColumnIndex(KEY_ROWID);
                   retvalue =  mDb.update(SQLITE_TABLE, updatevalue, KEY_ROWID + "=?",new String[] { String.valueOf(colId) });// + colId, null);
                   break;
             }
         }
         mDbHelper.close();
         return retvalue > 0;
     }

但密码从未更新过。重估值始终为0.可能出错? 感谢

2 个答案:

答案 0 :(得分:2)

而不是

long colId = mCursor.getColumnIndex(KEY_ROWID);

应该是

long colId = mCursor.getLong(getColumnIndex(KEY_ROWID));

答案 1 :(得分:0)

其实你做错了。如果要将多个记录插入数据库,则必须设置begin transaction。

您可以使用数据库事务。

如何在Android中使用数据库交易

If you want to start the transaction there is a method beginTransaction()
If you want to commit the transaction there is a method setTransactionSuccessful() which will commit the values in the database
If you had start the transaction you need to close the transaction so there is a method endTransaction() which will end your database transaction

现在有两个要点

If you want to set transaction successful you need to write setTransactionSuccessful() and then endTransaction() after beginTransaction()
If you want to rollback your transaction then you need to endTransaction() without committing the transaction by setTransactionSuccessful().

编辑:

EX。:

db.beginTransaction();
        try {
            // update table
            db.setTransactionSuccessful();

        }catch {
            //Error in between database transaction 
        }finally {
                db.endTransaction();

        }