IOS开发中如果用Sqlite库来写数据库会比较麻烦,FMDB是对sqlite的封装,有更加友好简洁的的语句。
1,FMDB下载地址:FMDB下载地址
2,导入src下的文件,使用时 #import "FMDatabase.h"
3,创建数据库
#define kDocDir [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]
#define dbPath [kDocDir stringByAppendingPathComponent:@"test.db"]
FMDatabase *db = [FMDatabase databaseWithPath:dbPath] ;
if (![db open]) {
NSLog(@"Could not open db.");
[db close];
}
4,创建表table1,3个字段id是整形,name是字符串,image是2进制的。
NSString *sqlStr =@"CREATE TABLE table1 (id integer, name text, image blob)";
BOOL res = [db executeUpdate:sqlStr];
if (!res) {
NSLog(@"error when creating db tabletable1");
[db close];
}
5,插入数据
int idvalue;
NSString *name;
NSData *data;
sqlStr = @"insert into table1 values (?,?,?)";
res = [db executeUpdate:sqlStr,idvalue,name,data];
if (!res) {
NSLog(@"error when insert intotable1");
[db close];
}
插入语句请不要这么写:
sqlStr = [NSString stringWithFormat:@"insert into table1 values (‘%@’,'%@','%@')",idvalue, name, data];
res = [db executeUpdate:sqlStr];
if (!res) {
NSLog(@"error when insert intotable1");
[db close];
}
这模样写的话2进制的data将不会保存到表里面。
6,查询数据
FMResultSet *s = [db executeQuery:@"SELECT * FROM table1"];
while ([s next]) {
int idvalue =[s intForColumn:@"id"];
NSString *name=[s stringForColumn:@"name"];
NSData *data=[s dataForColumn:@"image"];
}