// 1. 擷取沙盒路徑
NSString * path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
path = [path stringByAppendingPathComponent:@"FMDB.sqlite"];
NSLog(@"%@",path);
//2.建立FMDBDataBaseQueue對象并打開()
FMDatabaseQueue * queue = [[FMDatabaseQueue alloc]initWithPath:path];
[queue inDatabase:^(FMDatabase *db) {
NSString * createTable = @"create table if not exists t_person(person_id integer primary key autoincrement,person_name varchar,person_age integer)";// 沒有primary key會建立失敗
BOOL createFlag = [db executeUpdate:createTable];
if (createFlag) {
NSLog(@"建立成功");
}else{
NSLog(@"建立失敗");
}
}];
// // 3.增
// [queue inDatabase:^(FMDatabase *db) {
// NSString * insert = @"insert into t_person(person_name,person_age)values(?,?)";
// for (int i = 0; i < 3; i++) {
// NSString * name = [NSString stringWithFormat:@"jack%i",i];
int age = 20+i;
// NSString * age = [NSString stringWithFormat:@"%i",20+i];
//
NSLog(@"%@,%@",name,age);
// BOOL insertFlag = [db executeUpdate:insert,name,age];
// if (insertFlag) {
// NSLog(@"插入資料成功");
// }else{
// NSLog(@"插入資料失敗");
// }
// }
//
// }];
// 4.改
[queue inDatabase:^(FMDatabase *db) {
NSString * changeData = @"update t_person set person_age = 99 where person_id = 3";
[db executeUpdate:changeData];
}];
// 5.查
[queue inDatabase:^(FMDatabase *db) {
NSString * select = @"select * from t_person";
FMResultSet * resultSet = [db executeQuery:select];
}];
// 第一種情況 線程安全,解決同時取錢透支問題(上面解決)
// 第二種情況 轉賬:錢劃出去了,進賬:錢劃進來,轉出去了,但因為網絡斷網或者程式出錯等原因未到指定賬戶的問題(下面解決)
// 建立fmdbDataBase對象并打開
FMDatabase * db = [[FMDatabase alloc]initWithPath:path];
[db open];
//買書操作
// 1>扣錢
[db beginDeferredTransaction];//開啟事務
NSString * minusSql = @"update t_money set money=money-10";
BOOL deletaFlag = [db executeUpdate:minusSql];
NSString * addSql = @"insert into t_person (person_name,person_age)values('國文',80)";
BOOL addFlag = [db executeUpdate:addSql];
// 隻有都執行成功了才執行,如果有一條不成功就“復原”
if (deletaFlag&&addFlag) {
[db commit];// 送出事務
NSLog(@"commit");
}else{
[db rollback];// 復原事務
NSLog(@"rollback");
}
}