加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

在SQLite中使用事务

发布时间:2020-12-13 00:06:52 所属栏目:百科 来源:网络整理
导读:转自:www.eoeandroid.com/thread-201327-1-1.html 1.在数据库表person添加字段amount 2.在Person类中添加相应的amount 3.在PersonService添加payment()方法 public void payment(){ SQLiteDatabase db = dbOpenHelper.getWritableDatabase(); db.beginTrans

转自:www.eoeandroid.com/thread-201327-1-1.html

1.在数据库表person添加字段amount
2.在Person类中添加相应的amount
3.在PersonService添加payment()方法
  1. public void payment(){
  2. SQLiteDatabase db = dbOpenHelper.getWritableDatabase();
  3. db.beginTransaction(); //开户事务
  4. try{
  5. db.execSQL("update person set amount=amount-10 where personId=1");
  6. db.execSQL("update person set amount=amount-10 where personId=2");
  7. db.setTransactionSuccessful(); //设置事务的标志为True
  8. }finally{
  9. //为何要加try...catch
  10. //因为添加了db.setTransactionSuccessful(),若execSQL中出现问题
  11. //则不会执行db.endTransaction()
  12. db.endTransaction(); //结束事务,有2种情况:commit,rollback
  13. }
  14. //事务的提交或回滚是由事务的标志决定的
  15. //如果事务的标志为True,事务就会提交
  16. //否则事务就会回滚,默认情况下事务的标志为false
  17. }
复制代码 4.初始化amount值,便于调用
  1. public void testUpdateAmount() throws Exception{
  2. PersonService service = new PersonService(this.getContext());
  3. Person person1 = service.find(1);
  4. Person person2 = service.find(2);
  5. person1.setAmount(100);
  6. person2.setAmount(200);
  7. service.update(person1);
  8. service.update(person2);
  9. }
复制代码 5.在单元测试类PersonServiceTest中添加测试方法testPayment()
  1. public void testPayment() throws Exception{
  2. PersonService service = new PersonService(this.getContext());
  3. service.payment();
  4. }
复制代码

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读