银行转账
1)update person set amount=amount-10 where personid=1;
2)update person set amount=amount+10 where personid=2;
以上个例子为基础,修改DBOpenHelper类,增加amount字段升级数据库
[java]view plaincopy
- package cn.leigo.service;
- import android.content.Context;
- import android.database.sqlite.SQLiteDatabase;
- import android.database.sqlite.SQLiteOpenHelper;
- public class DBOpenHelper extends SQLiteOpenHelper {
-
- public DBOpenHelper(Context context) {
- super(context, "leigo.db", null, 3); //<包>/databases/
- }
-
- @Override
- public void onCreate(SQLiteDatabase db) {// 数据库第一次被创建的时候调用的
- db.execSQL("CREATE TABLE person (personid integer primary key autoincrement, name varchar(20))");
- }
-
- @Override
- public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
- db.execSQL("ALTER TABLE person ADD amount integer");
- }
-
- }
在Person类中增加amount变量:
[java]view plaincopy
- package cn.leigo.domain;
- public class Person {
- private Integer id;
- private String name;
- private String phone;
- private Integer amount;
-
- public Person() {
- }
-
- public Person(String name, String phone, Integer amount) {
- this.name = name;
- this.phone = phone;
- this.amount = amount;
- }
-
- public Person(Integer id, String name, String phone, Integer amount) {
- this.id = id;
- this.name = name;
- this.phone = phone;
- this.amount = amount;
- }
-
- public Integer getId() {
- return id;
- }
-
- public void setId(Integer id) {
- this.id = id;
- }
-
- public String getName() {
- return name;
- }
-
- public void setName(String name) {
- this.name = name;
- }
-
- public String getPhone() {
- return phone;
- }
-
- public void setPhone(String phone) {
- this.phone = phone;
- }
-
- public Integer getAmount() {
- return amount;
- }
-
- public void setAmount(Integer amount) {
- this.amount = amount;
- }
-
- @Override
- public String toString() {
- return "Person [id=" + id + ", name=" + name + ", phone=" + phone
- + ", amount=" + amount + "]";
- }
-
- }
修改报错的类
更新数据
[java]view plaincopy
- public void testUpdateAmount() throws Exception {
- PersonService service = new PersonService(getContext());
- Person person1 = service.find(1);
- Person person2 = service.find(2);
- person1.setAmount(100);
- person2.setAmount(50);
- service.update(person1);
- service.update(person2);
- }
[java]view plaincopy
- public void payment() {
- SQLiteDatabase db = dbOpenHelper.getWritableDatabase();
- // 开启事务
- db.beginTransaction();
- db.execSQL("UPDATE person SET amount=amount-10 where personid=1");
- //System.out.println(1/0);
- db.execSQL("UPDATE person SET amount=amount+10 where personid=2");
- db.setTransactionSuccessful();
- // 结束事务,有两种情况:commit、rollback
- // 事务的提交或者回滚是由事务的标识决定的,如果事务的标识为true,事务就会提交否则回滚,默认情况下事务的标识为false
- db.endTransaction();
- db.close();
-
- }
[java]view plaincopy
- public void testPayment() throws Exception {
- PersonService service = new PersonService(getContext());
- service.payment();
- }
将
[java]view plain