IOS開發(fā)中如果用Sqlite庫(kù)來(lái)寫數(shù)據(jù)庫(kù)會(huì)比較麻煩,F(xiàn)MDB是對(duì)sqlite的封裝,有更加友好簡(jiǎn)潔的的語(yǔ)句。
1,F(xiàn)MDB下載地址:FMDB下載地址
2,導(dǎo)入src下的文件,使用時(shí) #import "FMDatabase.h"
3,創(chuàng)建數(shù)據(jù)庫(kù)
#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,創(chuàng)建表table1,3個(gè)字段id是整形,name是字符串,image是2進(jìn)制的。
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,插入數(shù)據(jù)
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];
}
插入語(yǔ)句請(qǐng)不要這么寫:
sqlStr = [NSString stringWithFormat:@"insert into table1 values (‘%@’,'%@','%@')",idvalue, name, data];
res = [db executeUpdate:sqlStr];
if (!res) {
NSLog(@"error when insert intotable1");
[db close];
}
這模樣寫的話2進(jìn)制的data將不會(huì)保存到表里面。
6,查詢數(shù)據(jù)
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"];
}