Android开发中的SQLite事务处理,即beginTransaction()方法...

以下是Android API的官方注解

beginTransaction

Added in  API level 1
void beginTransaction ()

Begins a transaction in EXCLUSIVE mode.

Transactions can be nested. When the outer transaction is ended all of the work done in that transaction and all of the nested transactions will be committed or rolled back. The changes will be rolled back if any transaction is ended without being marked as clean (by calling setTransactionSuccessful). Otherwise they will be committed.

Here is the standard idiom for transactions:

   db.beginTransaction();
   try {
     ...
     db.setTransactionSuccessful();
   } finally {
     db.endTransaction();
   }
 


void beginTransaction()

Begins a transaction in EXCLUSIVE mode.

void setTransactionSuccessful()

Marks the current transaction as successful.

void endTransaction()

End a transaction.

英文不好的童鞋,用直白的来说就是:

使用SQLiteDatabase的beginTransaction()方法可以开启一个事务,程序执行到endTransaction() 方法时会检查事务的标志是否为成功,如果程序执行到endTransaction()之前调用了setTransactionSuccessful() 方法设置事务的标志为成功则提交事务,如果没有调用setTransactionSuccessful() 方法则回滚事务。事务处理应用:很多时候我们需要批量的向Sqlite中插入大量数据时,单独的使用添加方法导致应用响应缓慢, 因为sqlite插入数据的时候默认一条语句就是一个事务,有多少条数据就有多少次磁盘操作。如初始8000条记录也就是要8000次读写磁盘操作。同时也是为了保证数据的一致性,避免出现数据缺失等情况。

示例代码:

SQLiteDatabase db = dbOpenHelper.getWritableDatabase();

//开启事务
db.beginTransaction();
try{
            //批量处理操作
            //do something
           db.execSQL("SQL语句", new Object[]{});
           db.execSQL("SQL语句", new Object[]{});
            //设置事务标志为成功,当结束事务时就会提交事务
            db.setTransactionSuccessful();
} finally{
           //结束事务
          db.endTransaction();
}

下面是我写的一段代码:
if(!TextUtils.isEmpty(id_)&&!TextUtils.isEmpty(name_)&&!TextUtils.isEmpty(sex_)&&!TextUtils.isEmpty(phone_)){
     if (sex_.matches("[|]")){
         SQLiteDatabase db=dbHelper.getReadableDatabase();
         db.beginTransaction();//开启事务
         db.execSQL("delete from student where id=?",new String[]{oldID});
         Cursor cursor=db.rawQuery("select * from student where id=?",new String[]{id_});
         if (cursor.moveToNext()){
             Toast.makeText(this,"该学号已有学生注册,请重新输入!",Toast.LENGTH_LONG).show();
         }else {
             db.execSQL("insert into student(id,name,sex,password,phone,mathScore,chineseScore,englishScore) values (?,?,?,?,?,?,?,?)",new String[]{id_, name_, sex_, password_, phone_, mathScore, chineseScore, englishScore,});
             db.setTransactionSuccessful();//事务成功
             db.endTransaction();//结束事务
             Intent intent=new Intent(this,Manager_Activity.class);
             startActivity(intent);
         }
     }else {
         Toast.makeText(this,"请输入正确的性别!",Toast.LENGTH_LONG).show();

     }
}else {
    Toast.makeText(this,"姓名,性别,学号不能为空!",Toast.LENGTH_LONG).show();
}

其实  SQLite事务处理,即beginTransaction()方法...

使用起来的好处 除了可以批量处理sql语句外,还有的就是,没有提交事务成功,之前的sql语句就不会处理,相当于放在一个缓冲当中,到事务提交成功后,在一起执行,进行磁盘读写操作,只样的话,就算你之前步骤出错,也不会给数据库里添加没用的数据啦,



差不多就是这些了.好好吸收吧


你可能感兴趣的:(android开发,sqlite,api,Android)