FMDB是建立在SQLite之上的熔号,以OC的語法封裝了SQLite的C語言API,使用起來更加面向對象鸟整∫鳎可以存儲數(shù)據(jù)類型:TEXT(字符串)、INTEGER(整型)吃嘿、BLOB(二進制)祠乃、BOOLEAN(布爾)、DATE(數(shù)據(jù))兑燥。
- FMDatabase - 代表SQLite 數(shù)據(jù)庫的類亮瓷,用于執(zhí)行 SQL 語句
- FMResultSet - 代表在 FMDatabase中執(zhí)行查詢的結果的類
- FMDatabaseQueue - 如果您想在多線程上執(zhí)行查詢和更新,會使用這個類
示例
用法
-
創(chuàng)建數(shù)據(jù)庫
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
NSString *documents = [paths objectAtIndex:0];
NSString *path = [documents stringByAppendingPathComponent:@"sampleDB_1.0.0.db"];
_dataBase = [FMDatabase databaseWithPath:path];
if([_dataBase open]){
[_dataBase executeUpdate:@"CREATE TABLE IF NOT EXISTS sampleTable(name TEXT,age NEXT)"];
[_dataBase close];
NSLog(@"數(shù)據(jù)庫創(chuàng)建打開成功");
}else{
NSLog(@"數(shù)據(jù)庫創(chuàng)建打開失敗");
}
-
添加數(shù)據(jù)
NSArray *array = [NSArray array];
if ([self isOpenDatabese:_dataBase]) {
FMResultSet *result = [_dataBase executeQuery:[NSString stringWithFormat:@"SELECT * FROM sampleTable WHERE %@ LIMIT 1",[self getDBWhereStrWithDic:dic]]];
array = [self getArrWithFMResultSet:result keyTypes:@{@"name":@"TEXT", @"age":@"TEXT"}];}
//如果數(shù)據(jù)已存在降瞳,則更新數(shù)據(jù)
if (array.count) {
if ([self isOpenDatabese:_dataBase]) {
NSMutableString *sql = [[NSMutableString alloc] initWithString:[NSString stringWithFormat:@"UPDATE sampleTable SET %@ WHERE %@", [self getDBSetStrWithDic:dic], [self getDBWhereStrWithDic:dic]]];
[_dataBase executeUpdate:sql];
}
}else{ //否則插入數(shù)據(jù)
if ([self isOpenDatabese:_dataBase]) {
NSArray *keys = [dic allKeys];
NSArray *values = [dic allValues];
NSMutableString *sql = [[NSMutableString alloc] initWithString:[NSString stringWithFormat:@"INSERT INTO sampleTable ("]];
NSInteger count = 0;
for (NSString *key in keys) {
[sql appendString:key];
count ++;
if (count < [keys count]) {
[sql appendString:@", "];
}
}
[sql appendString:@") VALUES ("];
for (int i = 0; i < [values count]; i++) {
[sql appendString:@"?"];
if (i < [values count] - 1) {
[sql appendString:@","];
}
}
[sql appendString:@")"];
[_dataBase executeUpdate:sql withArgumentsInArray:values];
}
}
[_dataBase close];
-
刪除數(shù)據(jù)
// 刪除表中所有數(shù)據(jù)
if ([self isOpenDatabese:_dataBase]) {
[_dataBase executeUpdate:@"DELETE FROM sampleTable"];
}
[_dataBase close];
// 刪除單條數(shù)據(jù)sql語句
DELETE FROM sampleTable WHERE xx = ?
-
修改數(shù)據(jù)
if ([self isOpenDatabese:_dataBase]) {
NSMutableString *sql = [[NSMutableString alloc] initWithString:[NSString stringWithFormat:@"UPDATE sampleTable SET %@ WHERE %@", [self getDBSetStrWithDic:dic], [self getDBWhereStrWithDic:dic]]];
[_dataBase executeUpdate:sql];
}
-
數(shù)據(jù)查詢
FMResultSet *resRoute = [_dataBase executeQuery:@"select * from sampleTable"];