FMDB使用,iosfmdb使用
OS中原生的SQLite API在使用上大部分都是C語言代碼,在使用時,非常不便,因此便出現了很多針對SQLite封裝的第三方架構,其中FMDB就是其中一個優秀的架構,FMDB以OC的方式封裝了SQLite的C語言API, 它的出現使操作SQLite變得更簡潔易用,相比蘋果內建的Core Data架構,FMDB顯得更加輕量級,靈活。
FMDB的:https://github.com/ccgus/fmdb
在FMDB下載檔案後,工程中必須匯入如下檔案,並使用 libsqlite3.dylib 依賴包
FMDatabase : 一個單一的SQLite資料庫,用於執行SQL語句。
FMResultSet :執行查詢一個FMDatabase結果集。
FMDatabaseQueue :在多個線程來執行查詢和更新時會使用這個類
1、建立並且開啟資料庫
1、擷取資料庫物件
NSString *path=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0]; path=[path stringByAppendingPathComponent:@"test.sqlite"]; dataBase=[FMDatabase databaseWithPath:path];
2、開啟資料庫,如果不存在則建立並且開啟
BOOL open=[dataBase open]; if(open){ NSLog(@"資料庫開啟成功");}
3、建立表
NSString * create1=@"create table if not exists t_user(id integer autoincrement primary key,name varchar)"; BOOL c1= [dataBase executeUpdate:create1]; if(c1){ NSLog(@"建立表成功"); }
4、插入、刪除、修改資料
NSString * insertSql=@"insert into t_user(id,name) values(?,?)"; // 插入語句1 bool inflag1=[dataBase executeUpdate:insertSql,@(2),@"admin"]; // 插入語句2 bool inflag2=[dataBase executeUpdate:insertSql withArgumentsInArray:@[@"admin",@(5)]]; // 插入語句3 bool inflag3=[dataBase executeUpdateWithFormat:@"insert into t_user(id,name) values(%@,%d)",@"admin",6]; // 刪除語句 NSString * delete=@"delete from t_user"; BOOL dflag= [dataBase executeUpdate:delete]; if(dflag){ NSLog(@"刪除成功"); } // 修改語句 NSString *update=@" update t_user set name=? "; BOOL flag= [dataBase executeUpdate:update,@"zhangsan"]; if(flag){ NSLog(@"修改成功");}
5、查詢資料FMDB的FMResultSet提供了多個方法來擷取不同類型的資料
NSString * sql=@" select * from t_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); }
如果應用中使用了多線程操作資料庫,那麼就需要使用FMDatabaseQueue來保證安全執行緒了。 應用中不可在多個線程中共同使用一個FMDatabase對象操作資料庫,這樣會引起資料庫資料混亂。 為了多線程操作資料庫安全,FMDB使用了FMDatabaseQueue,使用FMDatabaseQueue很簡單,首先用一個資料庫檔案地址來初使化FMDatabaseQueue,然後就可以將一個閉包(block)傳入inDatabase方法中。 在閉包中操作資料庫,而不直接參与FMDatabase的管理
2、多線程操作
NSString *path=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0]; path=[path stringByAppendingPathComponent:@"test.sqlite"]; FMDatabaseQueue * queue=[FMDatabaseQueue databaseQueueWithPath:path]; [queue inDatabase:^(FMDatabase *db) { NSString * create=@"create table if not exists t_book(id integer,name varchar)"; BOOL c1= [db executeUpdate:create]; if(c1){ NSLog(@"成功"); } }]; [queue inDatabase:^(FMDatabase *db) { NSString * insertSql=@"insert into t_book(id,name) values(?,?)"; //插入語句1 bool inflag=[db executeUpdate:insertSql,@(2),@"admin"]; if(inflag){ NSLog(@"插入成功"); } }]; [queue inDatabase:^(FMDatabase *db) { FMResultSet * data=[db executeQuery:@" select * from t_book "]; while (data.next) { int ids=[data intForColumn:@"id"]; NSString *name=[data stringForColumn:@"name"]; NSLog(@"%@",name); NSLog(@"%i",ids); } }];