先引入头文件
#import <FMDB/FMDB.h>
- (void)viewDidLoad {
[super viewDidLoad];
//打开数据库
[self openDB];
//在子线程中,执行数据库插入操作
dispatch_async(dispatch_get_global_queue(0, 0), ^{
[self threadNotTransaction];
});
}
- (NSString*)dbPath{
NSString *dbPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSString *docPath = [dbPath stringByAppendingPathComponent:@"test.sqlite"];
NSLog(@"%@",dbPath);
return docPath;
}
- (void)openDB{
FMDatabase *database = [FMDatabase databaseWithPath:[self dbPath]];
/**
* 打开数据库,如果数据库打开成功,建表.如果打开失败就返回错误信息
*/
if([database open]){
BOOL isSuccess = [database executeUpdate:@"create table if not exists stu (name text)"];
if (isSuccess) {
NSLog(@"建表成功");
}else{
NSLog(@"建表失败");
}
}else{
NSLog(@"打开数据库失败");
}
}
- (void)threadNotTransaction{
//数据库文件的路径
FMDatabaseQueue *queue = [FMDatabaseQueue databaseQueueWithPath:[self dbPath]];
//将一组操作添加到非事务中
[queue inDatabase:^(FMDatabase *db) {
[db beginTransaction];//该句是将操作放入事务中 添加入事务操作.在不加本句时.该操作只是,该队列是串行队列,在运行时效率较慢.
BOOL isError = NO;
int temp = -1;
for (int i = 0 ; i < 10000; i++) {
isError = [db executeUpdate:@"insert into stu values (?)",@(i)];
if (!isError) { //说明 isError == NO.插入有问题
if(temp == -1){
temp = i;
}
}
}
if (isError) {
NSLog(@"所有插入动作成功");
}else{
NSLog(@"插入操作动作失败--%d",temp);
}
//提交事务
[db commit];//注意:在将操作添加到事务操作中后,一定要提交事务.
}];
}
网友评论