在Android应用程序中没有保存在DB中的记录

时间:2014-03-28 06:45:04

标签: android sqlite android-sqlite

在我的Android应用程序中,每次执行某些操作时,我都会在DB中保存记录。代码如下:

    Cursor histCurr = db.rawQuery("select * from HistStore order by seqNum", null);
    Log.d("DBHIST", histCurr.getCount() +" rows in DB0.");
    db.beginTransaction();
    long ret = db.insert("HistStore", null, newValues);
    db.endTransaction();
    if(ret<0){
        Log.d("DBHIST", "\r\n!!! Error to save history into DB!!!\r\n");
    }else{
        Log.d("DBHIST", ret+" rows inserted.");
        histCurr = db.rawQuery("select * from HistStore order by seqNum", null);
        Log.d("DBHIST", histCurr.getCount() +" rows in DB1.");
    }

日志是:

DBHIST(918):DB0中有30行。

DBHIST(918):插入了31行。

DBHIST(918):DB1中有30行。

我希望在最后一次打印中获得31行。为什么我没有得到它?

1 个答案:

答案 0 :(得分:1)

自您启动交易以来,您需要将其标记为成功,以使更改保持不变!

尝试这样做:

Cursor histCurr = db.rawQuery("select * from HistStore order by seqNum", null);
Log.d("DBHIST", histCurr.getCount() +" rows in DB0.");
db.beginTransaction();
long ret = -1;
try{
    ret = db.insert("HistStore", null, newValues);
    db.setTransactionSuccessful();
}
catch(Exception e){

}
finally{
    db.endTransaction();
}

if(ret<0){
    Log.d("DBHIST", "\r\n!!! Error to save history into DB!!!\r\n");
}else{
    Log.d("DBHIST", ret+" rows inserted.");
    histCurr = db.rawQuery("select * from HistStore order by seqNum", null);
    Log.d("DBHIST", histCurr.getCount() +" rows in DB1.");
}