在SQLite中使用事务

在SQLite中使用事务,第1张

概述转自:www.eoeandroid.com/thread-201327-1-1.html 1.在数据库表person添加字段amount 2.在Person类中添加相应的amount 3.在PersonService添加payment()方法 public void payment(){                 SQLiteDatabase db = dbOpenHelper.getWri

转自: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.beginTransaction(); //开户事务
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{
//为何要加try...catch
//因为添加了db.setTransactionSuccessful(),若execsql中出现问题
//则不会执行db.endTransaction()
db.endTransaction(); //结束事务,有2种情况:commit,rollback
}
//事务的提交或回滚是由事务的标志决定的
//如果事务的标志为True,事务就会提交
//否则事务就会回滚,默认情况下事务的标志为false
} 复制代码 4.初始化amount值,便于调用 public voID testUpdateAmount() throws Exception{
PersonService service = new PersonService(this.getContext());
Person person1 = service.find(1);
Person person2 = service.find(2);
person1.setAmount(100);
person2.setAmount(200);
service.update(person1);
service.update(person2);
} 复制代码 5.在单元测试类PersonServiceTest中添加测试方法testPayment() public voID testPayment() throws Exception{
PersonService service = new PersonService(this.getContext());
service.payment();
} 复制代码 总结

以上是内存溢出为你收集整理的在SQLite中使用事务全部内容,希望文章能够帮你解决在SQLite中使用事务所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/sjk/1181558.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-02
下一篇 2022-06-02

发表评论

登录后才能评论

评论列表(0条)

保存