1.导入
-1.三方库fmdb
-2.导入处理多线程的头文件
#import "FMDatabaseQueue.h"
-3.导入系统的sqlite
2.修改
-1.修改三方库的非arc改为arc:-fno-objc-arc
3.创建
-1.创建数据库创建数据库实例对象,用于处理多线程的问题
FMDatabaseQueue *queue;
-2.拼接存储地址,同数据库操作
NSString *cachePath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0];
NSString *filePath = [cachePath stringByAppendingPathComponent:@"t_user.sqlite"];
-3处理多线程安全问题,提供一个多线程实例,拼接路径
queue = [FMDatabaseQueue databaseQueueWithPath:filePath];
-4进行线程的操作
[queue inDatabase:^(FMDatabase *db) {
if ([db executeUpdate:@"create table if not exists t_user (id integer primary key autoincrement,name varchar(255),age varchar(255));"]) {
NSLog(@"成功创建");
}else{
NSLog(@"创建失败");
}
}];
4.操作
-1.增
[queue inDatabase:^(FMDatabase *db) {
if ([ db executeUpdate:@"insert into t_user (name,age) values (?,?)",@"lipp",@(500)]) {
NSLog(@"添加成功");
} else{
NSLog(@"添加失败");
}
}];
-2.删
[queue inDatabase:^(FMDatabase *db) {
-2.0 开启事务
[db beginTransaction];
if ([ db executeUpdate:@"delete from t_user where id = ?",@1]) {
NSLog(@"删除成功");
} else{
NSLog(@"删除失败");
-2.1还原,如果删除失败的情况
[db rollback];
}
-2.2如果进行多个删除,多个操作时候进行的操作,全部操作完成在去提交
[db commit];
}];
-3.改
[queue inDatabase:^(FMDatabase *db) {
if ([db executeUpdate:@"update t_user set name = ? where id = ?;",@"ppben",@1]) {
NSLog(@"修改成功");
}
else {
NSLog(@"修改失败");
}
}];
-4.查
[queue inDatabase:^(FMDatabase *db) {
FMResultSet *result = [db executeQuery:@"select * from t_user"];
while ([result next]) {
NSString *name = [result stringForColumn:@"name"];
NSString *age = [result stringForColumn:@"age"];
NSLog(@"%@----%@",name,age);
}
}];