//
//? ViewController.m
//? 04 - FMDB線程安全的用法
//
//? Created by 李洪強 on 2017/6/6.
//? Copyright ? 2017年 李洪強. All rights reserved.
//
?
#import "ViewController.h"
//導入頭文件
#import "FMDB.h"
@interface ViewController ()
@property(nonatomic,strong)FMDatabaseQueue *dataBaseQ;
@end
?
@implementation ViewController
?
- (void)viewDidLoad {
? ? [super viewDidLoad];
?
? ? NSString *path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject]stringByAppendingPathComponent:@"student"];
? ? FMDatabaseQueue *dataBaseQ = [FMDatabaseQueue databaseQueueWithPath:path];
? ? _dataBaseQ = dataBaseQ;
? ? [_dataBaseQ inDatabase:^(FMDatabase * _Nonnull db) {
?? ? ? ?
? ? ? ? BOOL success = [db open];
? ? ? ? if(success){
? ? ? ? ? ? NSLog(@"創建數據庫成功");
? ? ? ? ? ? //創建表
? ? ? ? ? ? NSString *str = @"CREATE TABLE IF NOT EXISTS t_student (id INTEGER PRIMARY KEY AUTOINCREMENT ,name TEXT NOT NULL,score REAL NOT NULL)";
? ? ? ? ? ? if([db executeUpdate:str]){
?? ? ? ? ? ? ? ?
? ? ? ? ? ? ? ? NSLog(@"創建表成功!");
? ? ? ? ? ? }else{
?? ? ? ? ? ? ? ?
? ? ? ? ? ? ? ? NSLog(@"創建表失敗!");
? ? ? ? ? ? }
? ? ? ? }else{
? ? ? ? ? ? NSLog(@"創建數據庫失敗");
? ? ? ? }
?? ? ? ?
? ? }];
?? ?
}
//增加數據
- (IBAction)insertData:(UIButton *)sender {
?? ?
? ? [_dataBaseQ inDatabase:^(FMDatabase * _Nonnull db) {
? ? ? ? for(int i = 0; i < 100 ; i++){
? ? ? ? ? ? NSString *strName = [NSString stringWithFormat:@"ming-yuexing-%d",i];
? ? ? ? ? ? NSString *sqlStr = [NSString stringWithFormat:@"INSERT INTO t_student (name , score) VALUES ('%@',%.2f)",strName,arc4random_uniform(1000)/10.0];
? ? ? ? ? ? BOOL success = [db executeUpdate:sqlStr];
? ? ? ? ? ? if(success){
? ? ? ? ? ? ? ? NSLog(@"添加成功");
? ? ? ? ? ? }else{
? ? ? ? ? ? ? ? NSLog(@"添加失敗");
? ? ? ? ? ? }
? ? ? ? }
?
? ? }];
?? ?
}
?
- (IBAction)selectData:(UIButton *)sender {
? ? [_dataBaseQ inDatabase:^(FMDatabase * _Nonnull db) {
? ? ? ? NSString *sqlStr = @"SELECT * FROM t_student WHERE score > 60.0 ORDER BY score DESC";
? ? ? ? //執行查詢語句
? ? ? ? FMResultSet *set = [db executeQuery:sqlStr];
? ? ? ? while ([set next]) {
? ? ? ? ? ? NSString *name = [set stringForColumn:@"name"];
? ? ? ? ? ? CGFloat score = [set doubleForColumn:@"score"];
? ? ? ? ? ? NSLog(@"name = %@ score = %f",name,score);
? ? ? ? }
? ? }];
?? ?
}
?
/*
?使用FMDB比sql的好處:
?線程安全
?公共資源在A使用的時候,B不能修改
?
?
?
?
?
?
?*/
?
@end