0

我正在尝试更新 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;
     }

但密码从未更新过。retvalue 始终为 0。可能有什么问题?谢谢

4

2 回答 2

2

代替

long colId = mCursor.getColumnIndex(KEY_ROWID);

它应该是

long colId = mCursor.getLong(getColumnIndex(KEY_ROWID));
于 2013-05-05T08:55:50.500 回答
0

其实你做错了。如果您有多个记录要插入数据库,则必须设置开始事务。

您可以为此使用数据库事务。

如何在 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().

编辑:

前任。:

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

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

        }
于 2013-05-05T08:56:23.327 回答