本來應用裡很多代碼,都是用原生的sqlite3 API,確實感到很不方便,API極不友好。昨天看到唐巧的博客,知道了FMDB,試用一下果然不錯,記錄一下
這個開源項目的github地址是:FMDB
安裝最方便的方式是用CocoaPods來安裝,見官方文檔。FMDB把SQL操作分為update和query,所以API不是executeUpdate,就是executeQuery,下面是幾個簡單的例子:
-(void) clearDeleteRecordForTable:(NSString*)tableName withRecords:(NSMutableArray*)deleteIds
{
NSString *dbFilePath = [YLSGlobalUtils getDatabaseFilePath];
FMDatabase *db = [FMDatabase databaseWithPath:dbFilePath];
NSString *sql = @"delete from tb_deleteRecord where table_name = ? and id = ?";
[db open];
for(NSString *deleteId in deleteIds){
[db executeUpdate:sql, tableName, deleteId];
}
[db close];
}-(NSMutableArray*) queryDeleteData:(NSString*)tableName
{
NSMutableArray *result = [NSMutableArray new];
NSString *dbFilePath = [YLSGlobalUtils getDatabaseFilePath];
FMDatabase *db = [FMDatabase databaseWithPath:dbFilePath];
[db open];
FMResultSet *rs = [db executeQuery:@"select id from tb_deleteRecord where upper(table_name) = upper(?)", tableName];
while ([rs next]) {
[result addObject:[rs objectForColumnName:@"id"]];
}
[db close];
return result;
}Thus, you SHOULD NOT do this (or anything like this):
[db executeUpdate:[NSString stringWithFormat:@"INSERT INTO myTable VALUES (%@)", @"this has \" lots of ' bizarre \" quotes '"]];
[db executeUpdate:@"INSERT INTO myTable VALUES (?)", @"this has \" lots of ' bizarre \" quotes '"];
@"select * from table where name = %@"
@"select * from table where name = '%@'"
-(NSMutableArray*) queryUpdateData:(NSString*)tableName
{
NSMutableArray *result = [NSMutableArray new];
NSString *dbFilePath = [YLSGlobalUtils getDatabaseFilePath];
FMDatabase *db = [FMDatabase databaseWithPath:dbFilePath];
[db open];
long now = [[NSDate date] timeIntervalSince1970];
FMResultSet *rs = [db executeQuery:@"select * from %@ where modify_date between ? and ? and (create_date not between ? and ?)", tableName, latestBackupTime, now, latestBackupTime, now];
while ([rs next]) {
[result addObject:[rs resultDictionary]];
}
[db close];
return result;
}總的來說,FMDB的API很直觀,也很方便。項目切換到FMDB的成本也非常低,強烈推薦試一下