FMDB简单使用
- FMDatabase的使用
- FMDatabaseQueue的使用
- 使用FMDatabaseQueue主要是为了线程安全,如果没有线程问题请使用FMDatabase,这样性能更优
- FMDB事务
示例代码:
@interface ViewController ()
//@property (nonatomic, strong) FMDatabase *db;
@property (nonatomic, strong) FMDatabaseQueue *dbQueue;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSString *sqliteFilePath = [path stringByAppendingPathComponent:@"student.sqlite"];
self.dbQueue = [FMDatabaseQueue databaseQueueWithPath:sqliteFilePath];
// 使用FMDatabaseQueue,为了线程安全!!!
[self.dbQueue inDatabase:^(FMDatabase *db) {
if ([db open])
{
// 创建表
NSString *sql = @"CREATE TABLE IF NOT EXISTS t_student(name TEXT , socre REAL, rank INTEGER , id INTEGER PRIMARY KEY AUTOINCREMENT);";
if ([db executeUpdate:sql])
{
NSLog(@"创建表成功");
}
else
{
NSLog(@"创建表失败");
}
}
else
{
NSLog(@"打开数据库失败");
}
}];
// 使用FMDatabase
/*
if ([self.dbQueue open])
{
// 创建表
NSString *sql = @"CREATE TABLE IF NOT EXISTS t_student(name TEXT , socre REAL, rank INTEGER , id INTEGER PRIMARY KEY AUTOINCREMENT);";
if ([self.dbQueue executeUpdate:sql])
{
NSLog(@"创建表成功");
}
else
{
NSLog(@"创建表失败");
}
}
else
{
NSLog(@"打开数据库失败");
}
*/
// 获取沙盒路径
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES);
NSString *ourDocumentPath =[documentPaths objectAtIndex:0];
NSLog(@"%@",ourDocumentPath);
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
// 插入
/*
if([self.db executeUpdate:@"INSERT INTO t_student (name, socre, rank) VALUES(?, ?, ?);", @"jack", @(99.8), @(1)])
{
NSLog(@"插入表成功");
}else
{
NSLog(@"插入表失败");
}
*/
// 查询
/*
NSString *sql = @"SELECT name, socre, rank, id FROM t_student;";
FMResultSet *set = [self.db executeQuery:sql];
while ([set next])
{
// NSString *str = [set stringForColumnIndex:0];
// double socre = [set doubleForColumnIndex:0];
// int rank = [set intForColumnIndex:0];
NSString *str = [set stringForColumn:@"name"];
double socre = [set doubleForColumn:@"socre"];
int rank = [set intForColumn:@"rank"];
NSLog(@"%@ %f %d", str, socre, rank);
}
*/
// 使用FMDatabaseQueue
[self.dbQueue inDatabase:^(FMDatabase *db) {
if([db executeUpdate:@"INSERT INTO t_student (name, socre, rank) VALUES(?, ?, ?);", @"jack", @(99.8), @(1)])
{
NSLog(@"插入表成功");
}else
{
NSLog(@"插入表失败");
}
}];
// FMDB事务,开启事务后,只有提交了事务才会真正的修改数据库
[self.dbQueue inTransaction:^(FMDatabase *db, BOOL *rollback) {
[db beginTransaction]; // 开启事务
if ([db executeUpdate:@"UPDATE t_student SET socre = 80 WHERE name = 'jack';"])
{
NSLog(@"更新成功");
}
else
{
NSLog(@"更新失败");
}
// 制造一个崩溃(银行存取款,断电问题),沙盒临时出现一个student.sqlite-journal文件
NSArray *array = @[@"123"];
array[3];
if ([db executeUpdate:@"UPDATE t_student SET socre = 0 WHERE name = 'jack';"])
{
NSLog(@"更新成功");
}
else
{
NSLog(@"更新失败");
}
[db commit]; // 提交事务
}];
}
@end