Android下数据库的事务
- 为什么需要事务:当我们要保证一个操作要么同时成功,要么同时失败时(最经典的就是银行转账)
- 重新介绍一个方法:onUpgrade方法
Called when the database needs to be upgraded. The implementation should use this method to drop tables, add tables, or do anything else it needs to upgrade to the new schema version.这个方法,当数据库的模式版本发生改变的时候就会被调用。即当你需要删除,创建,或者是其他任何一项需要改变数据库的版本的操作。
- 在这里我们需要先对数据库添加一个字段,在PersonSQLiteOpenHelper类中的构造方法中,手动修改版本号。
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.i(TAG,"数据库的版本变化了...");
db.execSQL("alter table person add account varchar(20)");
}
在测试代码中模拟转账的过程
public void testTransaction() throws Exception{
PersonSQLiteOpenHelper helper = new PersonSQLiteOpenHelper(getContext());
SQLiteDatabase db = helper.getWritableDatabase();
db.execSQL("update person set account=account-1000 where name=?", new Object[]{"zhangsan"});
db.execSQL("update person set account=account+1000 where name=?", new Object[]{"JEck_DE"});
db.close();
}
这段代码是有问题的,当程序执行到张三减1000元的时候,如果机器发生故障,下一句执行不到,就会导致JEck_DE收不到钱,而张三损失了1000元。谈钱伤感情啊~~,此时就需要引入数据库的事务
- db.beginTransaction();
- 方法介绍:
Begins a transaction in EXCLUSIVE mode.
- 示例代码:
db.beginTransaction();
try {
...
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
- 在try中执行业务逻辑。执行完业务逻辑后,android的一个特点就是,需要添加事务开启成功的标志,即db.setTransactionSuccessful();方法,如果不添加,默认是失败的。
- db.endTransaction();会根据上面的标志做出相应的操作,如果标志为成功,则数据提交成功,否则就回滚数据,不予提交
- 正确代码
public void testTransaction() throws Exception{
PersonSQLiteOpenHelper helper = new PersonSQLiteOpenHelper(getContext());
SQLiteDatabase db = helper.getWritableDatabase();
db.beginTransaction();
try {
db.execSQL("update person set account=account-1000 where name=?", new Object[]{"zhangsan"});
db.execSQL("update person set account=account+1000 where name=?", new Object[]{"JEck_DE"});
db.setTransactionSuccessful();
} finally {
db.endTransaction();
db.close();
}
}
——–测试成功
- 模拟异常
String s;//模拟空指针异常
public void testTransaction() throws Exception{
PersonSQLiteOpenHelper helper = new PersonSQLiteOpenHelper(getContext());
SQLiteDatabase db = helper.getWritableDatabase();
db.beginTransaction();
try {
db.execSQL("update person set account=account-1000 where name=?", new Object[]{"zhangsan"});
s.equals("haha");
db.execSQL("update person set account=account+1000 where name=?", new Object[]{"JEck_DE"});
db.setTransactionSuccessful();
} finally {
db.endTransaction();
db.close();
}
}
—–失败,转账不成功