标签:
iOS开发数据库篇—FMDB数据库队列
一、代码示例
1.需要先导入FMDB框架和头文件,由于该框架依赖于libsqlite库,所以还应该导入该库。
2.代码如下:
先插入数据,之后查询结果,打印如下:
3.代码说明
1 //插入数据 2 [self.queue inDatabase:^(FMDatabase *db) { 3 [db beginTransaction]; 4 [db executeUpdate:@"INSERT INTO t_person (name, age) VALUES (?, ?);",@"wendingding", @22]; 5 [db executeUpdate:@"INSERT INTO t_person (name, age) VALUES (?, ?);",@"wendingding", @23]; 6 [db executeUpdate:@"INSERT INTO t_person (name, age) VALUES (?, ?);",@"wendingding", @24]; 7 [db executeUpdate:@"INSERT INTO t_person (name, age) VALUES (?, ?);",@"wendingding", @25]; 8 [db commit]; 9 }];
如果中途出现问题,那么会自动回滚,也可以选择手动回滚。
1 //插入数据 2 [self.queue inDatabase:^(FMDatabase *db) { 3 [db beginTransaction]; 4 [db executeUpdate:@"INSERT INTO t_person (name, age) VALUES (?, ?);",@"wendingding", @22]; 5 [db executeUpdate:@"INSERT INTO t_person (name, age) VALUES (?, ?);",@"wendingding", @23]; 6 [db executeUpdate:@"INSERT INTO t_person (name, age) VALUES (?, ?);",@"wendingding", @24]; 7 [db rollback]; 8 [db executeUpdate:@"INSERT INTO t_person (name, age) VALUES (?, ?);",@"wendingding", @25]; 9 [db commit]; 10 }];
上面的代码。前三条插入语句是作废的。
事务处理的另一种方式:
1 [self.queue inTransaction:^(FMDatabase *db, BOOL *rollback) { 2 [db executeUpdate:@"INSERT INTO t_person (name, age) VALUES (?, ?);",@"wendingding", @22]; 3 [db executeUpdate:@"INSERT INTO t_person (name, age) VALUES (?, ?);",@"wendingding", @23]; 4 [db executeUpdate:@"INSERT INTO t_person (name, age) VALUES (?, ?);",@"wendingding", @24]; 5 }];
说明:先开事务,再开始事务,之后执行block中的代码段,最后提交事务。
标签:
原文地址:http://www.cnblogs.com/MJC-IOS-2010/p/5473686.html