ARC 和 MRC數據庫
FMDB做爲一個優秀的通用第三方數據庫框架,不管在ARC仍是MRC下,均可以自動匹配。多線程
使用框架
在FMDB中,有三個重要的類:spa
數據庫的建立和使用線程
代碼示例orm
- (void)viewDidLoad {對象
[super viewDidLoad];內存
//獲取沙盒路徑的方法一字符串
//實例化一個FMDatabase對象,並打開一個數據庫,若是沒有這個數據庫,就會建立一個數據庫string
// NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
//
// NSString *documentDirectory = [paths objectAtIndex:0];
//
// NSString *dbPath = [documentDirectory stringByAppendingPathComponent:@"Test.db"];
//獲取沙盒的路徑的方法二
NSString *dbPath = [NSString stringWithFormat:@"%@/Documents/xiaoming.db", NSHomeDirectory()];
NSLog(@"%@", dbPath);
//建立庫
FMDatabase *db = [FMDatabase databaseWithPath:dbPath];
//判斷若是數據庫打開失敗,就什麼都不作
if(![db open])
{
return;
}
//建立表
[db executeUpdate:@"CREATE TABLE Users(Name text, Age integer)"];
//插入數據
[db executeUpdate:@"INSERT INTO Users(Name, Age)VALUES(?,?)",@"Eric",[NSNumber numberWithInt:25]];
NSString *userName1 = [db stringForQuery:@"SELECT Name FROM Users WHERE Age = ?", @"25"];
NSLog(@"%@", userName1);
//更新數據
[db executeUpdate:@"UPDATE Users SET Name = ? WHERE Name = ?",@"Michael",@"Eric"];
//刪除數據
// [db executeUpdate:@"DELETE FROM Users WHERE Name = ?", @"Michael"];
//查詢數據
NSString *userName = [db stringForQuery:@"SELECT Name FROM Users WHERE Age = ?", @"25"];
NSLog(@"%@", userName);
//查詢多個數據,FMResultSet類,是一個結果集,返回多條數據,FMDB會將數據放在這個結果集中,而後在對這個結果集進行查詢便可
FMResultSet *res = [db executeQuery:@"SELECT * FROM Users"];
res = [db executeQuery:@"SELECT * FROM Users WHERE Age = ?", @"25"];
while ([res next]) {
NSString *name = [res stringForColumn:@"Name"];
NSString *age = [res stringForColumn:@"Age"];
NSLog(@"%@%@", name, age);
}
}
輸出結果