在SQLite中使用事务

来源:互联网 发布:小黑屋写作软件免费版 编辑:程序博客网 时间:2024/05/21 11:17

在SQLite中使用事务

用一个事务转账来实现SQLite的事务处理:
下面的person类是已经创建好了的表,在《创建数据库与完成数据添删改查(一)》中可以看到
<span style="white-space:pre"></span>1> update person set amount = amount-10 where personid=1;2> update person set amount = amount+10 where personid=2;
<span style="white-space:pre"></span>/** * 实现事务   :转账 */public void payment(){//DBOpenHelper这个类是创建数据库的类,在《创建数据库与完成数据添删改查(一)》中有SQLiteDatabase db = dbOpenHelper.getWritableDatabase();//要创建一个事务db.beginTransaction(); //开启事务//确保endTransaction会执行try{db.execSQL("update person set amount=amount-10 where personid=1");db.execSQL("update person set amount=amount+10 where personid=2");db.setTransactionSuccessful(); //设置事务的标志为true}finally{db.endTransaction();  //结束事务,有两种情况:commit,rollback,//事务的提交或回滚是由事务的标志决定的,    //true:事务就会提交,false:回滚(默认)}}


用一个测试类来执行一下:
//测试转账事务的准备:更新钱,也可以不要这步public void testUpdateAmount() throws Exception{PersonDao dao = new PersonDao(this.getContext());Person person1 = dao.find(1);Person person2 = dao.find(2);person1.setAmount(100);person2.setAmount(50);dao.update(person1);dao.update(person2);}//测试 事务   :转账public void testPayment() throws Exception{PersonDao dao = new PersonDao(this.getContext());dao.payment();}

执行后,就可以看到personid为1的人的10元钱转给了personid为2的人。

0 0
原创粉丝点击