public class TestTransaction extends AndroidTestCase
{
public void testTransaction() throws Exception{
//拿到数据库
PersonDBOpenHelp herper= new PersonDBOpenHelp(getContext());
SQLiteDatabase db = herper.getWritableDatabase();
//开启数据库事物
db.beginTransaction();
try{
db.execSQL( "update person set money=money-100
where name='zhangsan'");
//System.out.println(1/0);
db.execSQL( "update person set money=money+100
where name='zhangsan0'");
db.setTransactionSuccessful(); //如果没有标记数据库事物成功,数据会回滚
} finally{
db.endTransaction(); //关闭数据库事物
}
db.close();
}
}
------------------------------------------------------------------------------------------------
在内容提供者中开启事物:
/**
* 内容提供者中开启事物
* @throws Exception
*/
public void testBatch() throws Exception
{
ContentResolver resolver = getContext().getContentResolver();
ArrayList<ContentProviderOperation> list = new ArrayList<ContentProviderOperation>();
ContentProviderOperation operation1 = ContentProviderOperation.newInsert(rawContactsUri)
.withValue( "_id", null)
.build();
ContentProviderOperation operation2 = ContentProviderOperation.newInsert(dataUri)
.withValueBackReference( "raw_contact_id",
0) // 把同组第一个操作的结果作为值
.withValue( "mimetype", "vnd.android.cursor.item/name" )
.withValue( "data1", "CR")
.build();
ContentProviderOperation operation3 = ContentProviderOperation.newInsert(dataUri)
.withValueBackReference( "raw_contact_id",
0)
.withValue( "mimetype", "vnd.android.cursor.item/phone_v2" )
.withValue( "data1", "131999888888")
.build();
ContentProviderOperation operation4 = ContentProviderOperation.newInsert(dataUri)
.withValueBackReference( "raw_contact_id",
0)
.withValue( "mimetype", "vnd.android.cursor.item/email_v2" )
.withValue( "data1", "cr@hotmail.com")
.build();
list.add(operation1);
list.add(operation2);
list.add(operation3);
list.add(operation4);
resolver.applyBatch( "com.android.contacts",
list);
}
}