/**
資料庫三個步驟:
1,打開
2,操作
3,關閉
*/
#import "ViewController.h"
#import "FMDB.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
NSArray *pathesArr = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *path = [pathesArr firstObject];
NSString *dbPath = [path stringByAppendingPathComponent:@"sqlite.db"];
NSLog(@"%@",dbPath);
//考慮了線程安全的問題
FMDatabaseQueue *queue = [FMDatabaseQueue databaseQueueWithPath:dbPath];
[queue inDatabase:^(FMDatabase *db) {
FMResultSet *set = [db executeQuery:@"select id from myTable where name = 'wangbing';"];
//周遊所得到的結果
while ([set next]) {
int int_id = [set intForColumn:@"id"];
NSLog(@"%zi",int_id);
}
//結果集需要關閉
[set close];
[db close];
}];
//3,關閉
[queue close];
}
//不考慮線程安全的方式來操作資料
- (void)dbByDatabase{
NSArray *pathesArr = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *path = [pathesArr firstObject];
NSString *dbPath = [path stringByAppendingPathComponent:@"sqlite.db"];
NSLog(@"%@",dbPath);
//FMDatabase:資料庫類
FMDatabase *database = [FMDatabase databaseWithPath:dbPath];
if ([database open]) {
//2,操作
//建表
if ([database executeUpdate:@"create table if not exists 'myTable' (id int,name varchar(255),height float, primary key (id)) ;"]) {
NSLog(@"建表成功");
//插入資料
// if ([database executeUpdate:@"insert into myTable (id,name,height) values (1,'yhuihui',172);"]) {
// NSLog(@"插入資料成功");
// }
/*
//利用占位符的方式插入某條資料
if ([database executeUpdate:@"insert into myTable (id,name,height) values (?,?,?);",[NSNumber numberWithInt:3],@"wangshuo",[NSNumber numberWithFloat:178.0f]]) {
NSLog(@"插入資料成功");
}
*/
/*
//删除資料
if ([database executeUpdate:@"DELETE FROM myTable WHERE id = 1;"]) {
NSLog(@"删除資料成功");
}
*/
/*
if ([database executeUpdate:@"UPDATE myTable SET name = 'lixiujuan' WHERE id = 2;"]) {
NSLog(@"更新資料成功");
}
*/
FMResultSet *set = [database executeQuery:@"select id from myTable where name = 'wangshuo';"];
//周遊所得到的結果
while ([set next]) {
int int_id = [set intForColumn:@"id"];
NSLog(@"%zi",int_id);
}
//結果集需要關閉
[set close];
};
}
//3,關閉
[database close];
}