FMDB是建立在SQLite之上的,以OC的语法封装了SQLite的C语言API,使用起来更加面向对象。可以存储数据类型:TEXT(字符串)、INTEGER(整型)、BLOB(二进制)、BOOLEAN(布尔)、DATE(数据)。
- FMDatabase - 代表SQLite 数据库的类,用于执行 SQL 语句
- FMResultSet - 代表在 FMDatabase中执行查询的结果的类
- FMDatabaseQueue - 如果您想在多线程上执行查询和更新,会使用这个类
示例
用法
-
创建数据库
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(@"数据库创建打开成功");
}else{
NSLog(@"数据库创建打开失败");
}
-
添加数据
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"}];}
//如果数据已存在,则更新数据
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{ //否则插入数据
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];
-
删除数据
// 删除表中所有数据
if ([self isOpenDatabese:_dataBase]) {
[_dataBase executeUpdate:@"DELETE FROM sampleTable"];
}
[_dataBase close];
// 删除单条数据sql语句
DELETE FROM sampleTable WHERE xx = ?
-
修改数据
if ([self isOpenDatabese:_dataBase]) {
NSMutableString *sql = [[NSMutableString alloc] initWithString:[NSString stringWithFormat:@"UPDATE sampleTable SET %@ WHERE %@", [self getDBSetStrWithDic:dic], [self getDBWhereStrWithDic:dic]]];
[_dataBase executeUpdate:sql];
}
-
数据查询
FMResultSet *resRoute = [_dataBase executeQuery:@"select * from sampleTable"];