FMDB的下載地址是:https://github.com/ccgus/fmdb
工程中使用FMDB,必須導(dǎo)入libsqlite3.dylib 依賴包
FMDB常用類:
FMDatabase:一個(gè)單一的SQLite數(shù)據(jù)庫,用于執(zhí)行SQL語句
FMResultSet:執(zhí)行查詢一個(gè)FMDatabase結(jié)果集
FMDatabaseQueue:在多個(gè)線程來執(zhí)行查詢和更新時(shí)會(huì)使用這個(gè)類
以下是操作數(shù)據(jù)庫流程:
1、創(chuàng)建并且打開數(shù)據(jù)庫(根據(jù)存儲(chǔ)路徑)
// 1 獲取數(shù)據(jù)庫對(duì)象
NSString *path=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
path=[path stringByAppendingPathComponent:@"test.sqlite"];
dataBase=[FMDatabase databaseWithPath:path];
// 2 打開數(shù)據(jù)庫,如果不存在則創(chuàng)建并且打開
BOOL open=[dataBase open];
if(open){
NSLog(@"數(shù)據(jù)庫打開成功");
}
2、創(chuàng)建表
//3 創(chuàng)建表
NSString * create1=@"create table if not exists t_user(id integer autoincrement primary key,name varchar)";
BOOL c1= [dataBase executeUpdate:create1];
if(c1){
NSLog(@"創(chuàng)建表成功");
}
3、插入,刪除,修改數(shù)據(jù)利用executeUpdate
BOOL dflag= [dataBase executeUpdate:@“要執(zhí)行的sql語句”];
if(dflag){
}
4、查詢數(shù)據(jù)FMDB的FMResultSet提供了多個(gè)方法來獲取不同類型的數(shù)據(jù)
NString * sql=@" select * from table_user ";
FMResultSet *result=[dataBase executeQuery:sql];
while(result.next){
int ids=[result intForColumn:@"id"];
NSString * name=[result stringForColumn:@"name"];
int ids=[result intForColumnIndex:0];
NSString * name=[result stringForColumnIndex:1];
NSLog(@"%@,%d",name,ids);
}
如果應(yīng)用中使用了多線程操作數(shù)據(jù)庫,那么就需要使用FMDatabaseQueue來保證線程安全了。應(yīng)用中不可再多個(gè)線程中共同使用一個(gè)FMDatabase對(duì)象操作數(shù)據(jù)庫,這樣會(huì)引起數(shù)據(jù)庫數(shù)據(jù)混亂。為了多線程操作數(shù)據(jù)庫安全,F(xiàn)MDB使用了FMDatabaseQueue,F(xiàn)MDatabaseQueue使用了BLOCK傳入inDatabase的方法,在block中操作數(shù)據(jù),不直接參與FMDatabase的管理。
多線程操作數(shù)據(jù)庫如下:
1、創(chuàng)建并且打開數(shù)據(jù)庫(根據(jù)存儲(chǔ)路徑)
// 1 獲取數(shù)據(jù)庫對(duì)象
NSString *path=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
path=[path stringByAppendingPathComponent:@"test.sqlite"];
FMDatabaseQueue * queue=[FMDatabaseQueue databaseQueueWithPath:path];
2、創(chuàng)建表
[queue inDatabase:^(FMDatabase *db) {
NSString * create=@"create table if not exists talbe_user(id integer,name varchar)";
BOOL c1= [db executeUpdate:create];
if(c1){
NSLog(@"成功");
}
}];
3、插入,刪除,修改表
[queue inDatabase:^(FMDatabase *db) {
NSString * insertSql=@"insert into talbe_user(id,name) values(?,?)";
//插入語句1
bool inflag=[db executeUpdate:insertSql,@(2),@"admin"];
if(inflag){
NSLog(@"插入成功");
}
}];
4、查詢表
[queue inDatabase:^(FMDatabase *db) {
FMResultSet * data=[db executeQuery:@" select * from table_user "];
while (data.next) {
int ids=[data intForColumn:@"id"];
NSString *name=[data stringForColumn:@"name"];
NSLog(@"%@",name);
NSLog(@"%i",ids);
}
}];