sqlite(2、事务)
sqlite默认每条执行语句都是一个事务,因此增加事务除了会进行原子性的保护外,也可提升性能,减少磁盘操作。使用SQLite的beginTransaction()方法可以开启一个事务,执行到endTransaction()方法是会检查事务的标志是否为成功,如果成功则提交事务,否则回滚事务。
当应用程序需要提交事务,必须在程序到endTransaction()方法之前使用setTransactionSuccessfull()方法设置事务的标志为成功。若果如果不调用setTransactionSuccessful()不设置事务标志的话,默认回滚。
程序实例如下:
SQLiteDatabase db = openOrCreateDatabase("demo.db", this.MODE_PRIVATE, null);
db.execSQL("CREATE TABLE IF NOT EXISTS users (_id INTEGER PRIMARY KEY AUTOINCREMENT, username VARCHAR, password VARCHAR)");
//开启事务
db.beginTransaction();
try
{
db.execSQL("INSERT INTO users VALUES (NULL,'fredric1','fredricpassword1')");
db.execSQL("INSERT INTO users VALUES (NULL,'fredric2','fredricpassword2')");
db.execSQL("INSERT INTO users VALUES (NULL,'fredric3','fredricpassword3')");
db.execSQL("INSERT INTO users VALUES (NULL,'fredric4','fredricpassword4')");
//设置事务标志为成功,当结束事务时就会提交事务
db.setTransactionSuccessful();
}
finally
{
//结束事务
db.endTransaction();
Cursor cursor = db.rawQuery("SELECT * FROM users", null);
while (cursor.moveToNext()) {
Log.i(TAG_ACTIVITY, cursor.getString(cursor.getColumnIndex("username")));
Log.i(TAG_ACTIVITY, cursor.getString(cursor.getColumnIndex("password")));
}
cursor.close();
}
}
浙公网安备 33010602011771号