Android中sqlite事物控制

使用SQLiteDatabase的beginTransaction()方法可以开启一个事务,程序执行到endTransaction() 方法时会检查事务的标志是否为成功,如果程序执行到endTransaction()之前调用了setTransactionSuccessful() 方法设置事务的标志为成功则提交事务,如果没有调用setTransactionSuccessful() 方法则回滚事务。使用例子如下:

public void testTransaction() {
		PersonSQLiteOpenHelper openHelper = new PersonSQLiteOpenHelper(getContext());
		SQLiteDatabase db = openHelper.getWritableDatabase();
		
		if(db.isOpen()) {
			
			try {
				// 开启事务
				db.beginTransaction();
				
				// 1. 从张三账户中扣1000块钱
				db.execSQL("update person set balance = balance - 1000 where name = 'zhangsan';");
				
				// ATM机, 挂掉了.
				// int result = 10 / 0;
				
				// 2. 向李四账户中加1000块钱
				db.execSQL("update person set balance = balance + 1000 where name = 'lisi';");
				
				// 标记事务成功
				db.setTransactionSuccessful();
			} finally {
				// 停止事务
				db.endTransaction();
			}
			db.close();
		}
	}
	
	public void testTransactionInsert() {
		PersonSQLiteOpenHelper openHelper = new PersonSQLiteOpenHelper(getContext());
		SQLiteDatabase db = openHelper.getWritableDatabase();
		
		if(db.isOpen()) {
			
			// 1. 记住当前的时间
			long start = System.currentTimeMillis();
			
			// 2. 开始添加数据
			try {
				db.beginTransaction();
				for (int i = 0; i < 10000; i++) {
					db.execSQL("insert into person(name, age, balance) values('wang" + i + "', " + (10 + i) + ", " + (10000 + i) + ")");
				}
				db.setTransactionSuccessful();
			} finally {
				db.endTransaction();
			}
			
			// 3. 记住结束时间, 计算耗时时间
			long end = System.currentTimeMillis();
			
			long diff = end - start;
			Log.i(TAG, "耗时: " + diff + "毫秒");
			
			db.close();
		}
	}
}


你可能感兴趣的:(Android事物)