原文:# iOS本地存儲-數(shù)據(jù)庫(FMDB)
//創(chuàng)建數(shù)據(jù)庫中的表
BOOL stuSql = [db executeUpdate:@"create table if not exists stu(stuid integer primary key autoincrement, name varchar(255),sex varchar(255),age integer)"];
//向數(shù)據(jù)庫中插入數(shù)據(jù)
NSString *insertSql = @"insert into stu(stuid,name,sex,age) values(?,?,?,?)";
BOOL success = [db executeUpdate:insertSql,@"1",[NSString stringWithFormat:@"zxm"],@"男",@20];
//查詢數(shù)據(jù)庫 //查詢所有的數(shù)據(jù)庫數(shù)據(jù)
NSString *selectSql = @"select *from stu";
FMResultSet *result = [db executeQuery:selectSql];
while ([result next]) {
NSLog(@"%@ %@ %@ %d",[result stringForColumn:@"stuid"],[result stringForColumn:@"name"],[result stringForColumn:@"sex"],[result intForColumn:@"age"]);
}
//通過某個字段檢查是否存在數(shù)據(jù)
NSString * querySql = [NSString stringWithFormat:@"select * from stu where %@='%@'", table,@"男",@20];
//清空數(shù)據(jù)庫
NSString *deleteSql = @"delete from stu";
BOOL success = [db executeUpdate:deleteSql];
//修改數(shù)據(jù)庫中的數(shù)據(jù) //tian6是新值 代替數(shù)據(jù)庫中name = tian1的值
NSString *updateSql = @"update stu set name = ? where name = ?";
BOOL success = [db executeUpdate:updateSql,@"tian6",@"tian1"];
iOS中原聲的SQLite API在進行數(shù)據(jù)存儲的時候熙揍,需要使用C語言中的函數(shù)斩郎,操作比較麻煩悉稠,于是就出現(xiàn)了一系列將SQLite封裝的庫实蓬。本文講解的FMDB就是其中的一個定鸟。
FMDB PK Sqlite
優(yōu)點:
1.對多線程的并發(fā)操作進行了處理而涉,所以是線程安全的
2.以O(shè)C的方式封裝了SQLite的C語言API,使用起來更加方便
3.FMDB是輕量級框架 使用靈活
缺點:
因為它是OC的語言封裝的联予,只能在ios開發(fā)的時候使用啼县,所以在實現(xiàn)跨平臺操作的時候存在局限性。
FMDB框架中重要的框架類
FMDataBase
FMDataBase對象就代表一個單獨的SQLite數(shù)據(jù)庫 用來執(zhí)行SQL語句
FMResultSet
使用FNDataBase執(zhí)行查詢后的結(jié)果集
FMDataBaseQueue
用于在多線程中執(zhí)行多個查詢或更新 他是線程安全的
下面通過一個例子來講解FMDB的具體用法
首先使用FMDB需要導(dǎo)入libsqlite3.0框架沸久,在需要數(shù)據(jù)庫的類中引入
FMDatabase.h.``
創(chuàng)建數(shù)據(jù)庫
例子中用到的測試模型類
[](javascript:void(0); "復(fù)制代碼")
<pre style="margin: 0px; white-space: pre-wrap; word-wrap: break-word; padding: 0px; list-style-type: none; list-style-image: none; font-family: "Courier New" !important; font-size: 12px !important;">#import <Foundation/Foundation.h>
@interface student : NSObject
@property (nonatomic,assign) int stuid;
@property (nonatomic,copy) NSString *name;
@property (nonatomic,copy) NSString *sex;
@property (nonatomic,assign) int age; @end</pre>
[](javascript:void(0); "復(fù)制代碼")
創(chuàng)建數(shù)據(jù)庫的代碼
[](javascript:void(0); "復(fù)制代碼")
<pre style="margin: 0px; white-space: pre-wrap; word-wrap: break-word; padding: 0px; list-style-type: none; list-style-image: none; font-family: "Courier New" !important; font-size: 12px !important;">- (void)createDataBase { //創(chuàng)建數(shù)據(jù)庫 //1>獲取數(shù)據(jù)庫文件的路徑
NSString *docpath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *fileName = [docpath stringByAppendingPathComponent:@"student.sqlite"]; //初始化數(shù)據(jù)庫
db = [[FMDatabase alloc] initWithPath:fileName]; //創(chuàng)建數(shù)據(jù)庫中的表
if (db) { if ([db open]) {
BOOL stuSql = [db executeUpdate:@"create table if not exists stu(stuid integer primary key autoincrement, name varchar(255),sex varchar(255),age integer)"]; if (stuSql) {
NSLog(@"數(shù)據(jù)庫創(chuàng)建表成功");
}else {
NSLog(@"創(chuàng)建表失敗");
}
}else {
NSLog(@"數(shù)據(jù)庫沒有打開");
}
}else {
NSLog(@"創(chuàng)建數(shù)據(jù)庫失敗");
}
}</pre>
](javascript:void(0); "復(fù)制代碼")
注意創(chuàng)建數(shù)據(jù)庫時路徑的問題 路徑可以是以下三種方式之一
1.文件路徑 該文件路徑真實存在季眷,如果不存在回自動創(chuàng)建
2.空字符串@"" 表示會在臨時目錄里創(chuàng)建一個空的數(shù)據(jù)庫 當(dāng)FMDataBase連接關(guān)閉時 文件也會被刪除
3.NULL 將創(chuàng)建一個內(nèi)在數(shù)據(jù)庫 同樣的 當(dāng)FMDataBase連接關(guān)閉時 數(shù)據(jù)將會被銷毀
向數(shù)據(jù)庫中添加數(shù)據(jù) 查找數(shù)據(jù) 和 刪除數(shù)據(jù)
[](javascript:void(0); "復(fù)制代碼")
<pre style="margin: 0px; white-space: pre-wrap; word-wrap: break-word; padding: 0px; list-style-type: none; list-style-image: none; font-family: "Courier New" !important; font-size: 12px !important;">//向數(shù)據(jù)庫中插入數(shù)據(jù)
-
(void)insertDataToDb{
NSArray *array = @[@"13141",@"13142",@"13143",@"13144",@"13145"]; for (int i = 0; i < 5; i ++) {
NSString *insertSql = @"insert into stu(stuid,name,sex,age) values(?,?,?,?)";BOOL success = [db executeUpdate:insertSql,array[i],[NSString stringWithFormat:@"tian%d",i],@"男",@20]; if (success) { NSLog(@"數(shù)據(jù)插入成功"); }
}
} //查詢數(shù)據(jù)庫 //查詢所有的數(shù)據(jù)庫數(shù)據(jù) (void)selectDataFormDb{
NSString *selectSql = @"select *from stu";
FMResultSet *result = [db executeQuery:selectSql]; while ([result next]) {
NSLog(@"%@ %@ %@ %d",[result stringForColumn:@"stuid"],[result stringForColumn:@"name"],[result stringForColumn:@"sex"],[result intForColumn:@"age"]);
}
} //清空數(shù)據(jù)庫
- (void)deleteAllDbData {
NSString *deleteSql = @"delete from stu";
BOOL success = [db executeUpdate:deleteSql]; if (success) {
NSLog(@"刪除數(shù)據(jù)成功");
}
}</pre>
[[圖片上傳失敗...(image-15801f-1529369304986)]](javascript:void(0); "復(fù)制代碼")
清空數(shù)據(jù)庫之前的打印結(jié)果是
[](javascript:void(0); "復(fù)制代碼")
<pre style="margin: 0px; white-space: pre-wrap; word-wrap: break-word; padding: 0px; list-style-type: none; list-style-image: none; font-family: "Courier New" !important; font-size: 12px !important;">FMDB[1530:98012] 數(shù)據(jù)插入成功
FMDB[1530:98012] 數(shù)據(jù)插入成功
FMDB[1530:98012] 數(shù)據(jù)插入成功
FMDB[1530:98012] 數(shù)據(jù)插入成功
FMDB[1530:98012] 數(shù)據(jù)插入成功
FMDB[1530:98012] 13141 tian0 男 20 FMDB[1530:98012] 13142 tian1 男 20 FMDB[1530:98012] 13143 tian2 男 20 FMDB[1530:98012] 13144 tian3 男 20 FMDB[1530:98012] 13145 tian4 男 20</pre>
](javascript:void(0); "復(fù)制代碼")
修改數(shù)據(jù)
[](javascript:void(0); "復(fù)制代碼")
<pre style="margin: 0px; white-space: pre-wrap; word-wrap: break-word; padding: 0px; list-style-type: none; list-style-image: none; font-family: "Courier New" !important; font-size: 12px !important;">//修改數(shù)據(jù)庫中的數(shù)據(jù)
- (void)updateDbData { //tian6是新值 代替數(shù)據(jù)庫中name = tian1的值
NSString *updateSql = @"update stu set name = ? where name = ?";
BOOL success = [db executeUpdate:updateSql,@"tian6",@"tian1"]; if (success) {
[self selectDataFormDb];
}
} //結(jié)果
2016-12-12 13:44:45.489 FMDB[1604:103750] 13141 tian0 男 20
2016-12-12 13:44:45.489 FMDB[1604:103750] 13142 tian6 男 20
2016-12-12 13:44:45.489 FMDB[1604:103750] 13143 tian2 男 20
2016-12-12 13:44:45.489 FMDB[1604:103750] 13144 tian3 男 20
2016-12-12 13:44:45.489 FMDB[1604:103750] 13145 tian4 男 20</pre>
](javascript:void(0); "復(fù)制代碼")
下面是另寫的一個完整的例子
student.h文件
[](javascript:void(0); "復(fù)制代碼")
<pre style="margin: 0px; white-space: pre-wrap; word-wrap: break-word; padding: 0px; list-style-type: none; list-style-image: none; font-family: "Courier New" !important; font-size: 12px !important;">#import "ViewController.h"
@interface Student : NSObject
@property(nonatomic,strong)NSStringstuid;
@property(nonatomic,strong)NSStringstuname;
@property(nonatomic,strong)NSString*stuage;
@property(nonatomic,strong)NSData * stuheadimage; @end</pre>
](javascript:void(0); "復(fù)制代碼")
studentManager.h文件
[](javascript:void(0); "復(fù)制代碼")
<pre style="margin: 0px; white-space: pre-wrap; word-wrap: break-word; padding: 0px; list-style-type: none; list-style-image: none; font-family: "Courier New" !important; font-size: 12px !important;">#import <Foundation/Foundation.h>
import "Student.h"
@interface studentDBManager : NSObject +(instancetype)shareManager; //添加一條數(shù)據(jù)到數(shù)據(jù)表中
-(BOOL)addDataWithModel:(Student*)student ConditionString:(NSString *)conditionStr andconditionValue:(NSString *)conditionValue andtable:(NSString * )table; //通過某個字段刪除一條數(shù)據(jù);
-(BOOL)deleteDataWithConditionString:(NSString *)conditionStr andconditionValue:(NSString *)conditionValue andtable:(NSString * )table; // 刪除所有的記錄
- (BOOL)deleteAllDataWithtable:(NSString )table; //查詢一條數(shù)據(jù)卷胯; //1.查詢?nèi)繑?shù)據(jù)子刮,2根據(jù)特定字段查詢數(shù)據(jù);
-(NSArray * )getDataWithconditionString:(NSString * )conditionstr andConditionValue:(NSString )conditionValue allData:(BOOL)isAllData andTable:(NSString )table; //修改某條數(shù)據(jù)
-(BOOL)updateDataWithString:(NSString)NewStr andNewStrValue:(id)NewStrValue andConditionStr:(NSString)conditionStr andConditionValue:(NSString)conditionValue andTable:(NSString*)table; @end</pre>
](javascript:void(0); "復(fù)制代碼")
studentManager.m文件
[](javascript:void(0); "復(fù)制代碼")
<pre style="margin: 0px; white-space: pre-wrap; word-wrap: break-word; padding: 0px; list-style-type: none; list-style-image: none; font-family: "Courier New" !important; font-size: 12px !important;">#import "studentDBManager.h"
import "FMDB.h"
static studentDBManager * manager=nil; @implementation studentDBManager
{
FMDatabase * _database;
} +(instancetype)shareManager
{ static dispatch_once_t onceTocken;
dispatch_once(&onceTocken, ^{
manager=[[studentDBManager alloc]init];
}); return manager;
} -(instancetype)init
{ if (self=[super init]) { // 創(chuàng)建數(shù)據(jù)庫窑睁,使用FMDB第三方框架 // 創(chuàng)建數(shù)據(jù)庫文件保存路徑..../Documents/app.sqlite // sqlite數(shù)據(jù)庫(輕量級的數(shù)據(jù)庫)挺峡,它就是一個普通的文件,txt是一樣的担钮,只不過其中的文件內(nèi)容不一樣橱赠。 // 注:sqlite文件中定義了你的數(shù)據(jù)庫表、數(shù)據(jù)內(nèi)容 // MySql箫津、Oracle這些大型的數(shù)據(jù)庫狭姨,它需要一個管理服務(wù)宰啦,是一整套的。
NSString * dbPath=[NSString stringWithFormat:@"%@/Documents/app.sqlite",NSHomeDirectory()];
NSLog(@"%@",dbPath); // 創(chuàng)建FMDatabase // 如果在目錄下沒有這個數(shù)據(jù)庫文件饼拍,將創(chuàng)建該文件赡模。
_database=[[FMDatabase alloc]initWithPath:dbPath]; if (_database) { if ([_database open]) { //第一步:創(chuàng)建學(xué)生信息表
NSString *stuSql = @"create table if not exists stu(stuid varchar(255),name varchar(255),age varchar(255),headimage binary)"; //第一步:創(chuàng)建學(xué)生信息表
NSString * createSql=@"create table if not exists stu(stuid varchar(255),name varchar(255),age varchar(255),headimage binary)"; // FMDatabase執(zhí)行sql語句 // 當(dāng)數(shù)據(jù)庫文件創(chuàng)建完成時,首先創(chuàng)建數(shù)據(jù)表师抄,如果沒有這個表漓柑,就去創(chuàng)建,有了就不創(chuàng)建
BOOL creatableSucess=[_database executeUpdate:createSql];
NSLog(@"創(chuàng)建表%d",creatableSucess);
} else {
NSLog(@"打開數(shù)據(jù)庫失敗");
}
} else {
NSLog(@"創(chuàng)建數(shù)據(jù)庫失敗");
}
} return self;
} ////通過某個字段檢查是否存在數(shù)據(jù)
-
(BOOL)isExsitsWithConditionString:(NSString *)conditionStr andConditionValue:(NSString *)conditionValue andtable:(NSString *)table
{
NSString * querySql = [NSString stringWithFormat:@"select * from %@ where %@='%@'", table,conditionStr,conditionValue];FMResultSet * set = [_database executeQuery:querySql]; // 判斷是否已存在數(shù)據(jù)
if ([set next]) { return YES;
} else
return NO;
} //添加一條數(shù)據(jù)到數(shù)據(jù)表中
-(BOOL)addDataWithModel:(Student*)student ConditionString:(NSString *)conditionStr andconditionValue:(NSString *)conditionValue andtable:(NSString * )table
{ // 如果已存在數(shù)據(jù)叨吮,先刪除已有的數(shù)據(jù)欺缘,再添加新數(shù)據(jù)
BOOL isExsits = [self isExsitsWithConditionString:conditionStr andConditionValue:conditionValue andtable:table]; if (isExsits) {
[self deleteDataWithConditionString:conditionStr andconditionValue:conditionValue andtable:table];
} // 添加新數(shù)據(jù)
NSString * insertSql = [NSString stringWithFormat:@"insert into %@ values (?,?,?,?)",table];BOOL success = [_database executeUpdate:insertSql,student.stuid ,student.stuname,student.stuage,student.stuheadimage];
NSLog(@"%d",success); return success;
} //通過某個字段刪除一條數(shù)據(jù);
-(BOOL)deleteDataWithConditionString:(NSString *)conditionStr andconditionValue:(NSString *)conditionValue andtable:(NSString * )table
{ //刪除之前先判斷該數(shù)據(jù)是否存在挤安;
BOOL isExsits=[self isExsitsWithConditionString:conditionStr andConditionValue:conditionValue andtable:table]; if (isExsits) {
NSString * deleteSql = [NSString stringWithFormat:@"delete from %@ where %@='%@'",table,conditionStr,conditionValue];
BOOL success=[_database executeUpdate:deleteSql]; return success;
} else {
NSLog(@"該記錄不存在"); return NO;
}
} // 刪除所有的記錄
-
(BOOL)deleteAllDataWithtable:(NSString *)table
{
NSString * deletesql=[NSString stringWithFormat:@"delete from %@",table];BOOL success = [_database executeUpdate:deletesql]; return success;
} //查詢一條數(shù)據(jù); //1.查詢?nèi)繑?shù)據(jù)丧鸯,2根據(jù)特定字段查詢數(shù)據(jù)蛤铜;
-(NSArray * )getDataWithconditionString:(NSString * )conditionstr andConditionValue:(NSString *)conditionValue allData:(BOOL)isAllData andTable:(NSString *)table
{
NSString * getSql; if (isAllData) {
getSql =[NSString stringWithFormat:@"select * from %@",table];
} else {
getSql = [NSString stringWithFormat:@"select * from %@ where %@='%@'",table,conditionstr,conditionValue];
} // 執(zhí)行sql
FMResultSet * set = [_database executeQuery:getSql]; // 循環(huán)遍歷取出數(shù)據(jù)
NSMutableArray * array = [[NSMutableArray alloc] init]; while ([set next]) {
Student * model = [[Student alloc] init]; // 從結(jié)果集中獲取數(shù)據(jù) // 注:sqlite數(shù)據(jù)庫不區(qū)別分大小寫
model.stuid = [set stringForColumn:@"stuid"];
model.stuname= [set stringForColumn:@"name"];
model.stuage=[set stringForColumn:@"age"];
model.stuheadimage=[set dataForColumn:@"headimage"];
[array addObject:model];
} //備注:stuheadimage的使用, UIImage * image=[UIImage imageWithData:imageData];
return array;
} //修改某條數(shù)據(jù)
-(BOOL)updateDataWithString:(NSString)NewStr andNewStrValue:(id)NewStrValue andConditionStr:(NSString)conditionStr andConditionValue:(NSString)conditionValue andTable:(NSString)table
{
NSString * updateSql=[NSString stringWithFormat:@"UPDATE %@ SET %@='%@' WHERE %@='%@';",table,NewStr,NewStrValue,conditionStr,conditionValue];
BOOL success= [_database executeUpdate:updateSql]; return success;
}</pre>
](javascript:void(0); "復(fù)制代碼")
數(shù)據(jù)庫的多線程操作
如果應(yīng)用中使用了多線程操作數(shù)據(jù)庫丛肢,那么就需要使用FMDatabaseQueue來保證線程安全了围肥。 應(yīng)用中不可在多個線程中共同使用一個FMDatabase對象操作數(shù)據(jù)庫,這樣會引起數(shù)據(jù)庫數(shù)據(jù)混亂蜂怎。 為了多線程操作數(shù)據(jù)庫安全穆刻,F(xiàn)MDB使用了FMDatabaseQueue,使用FMDatabaseQueue很簡單杠步,首先用一個數(shù)據(jù)庫文件地址來初使化FMDatabaseQueue氢伟,然后就可以將一個閉包(block)傳入inDatabase方法中。 在閉包中操作數(shù)據(jù)庫幽歼,而不直接參與FMDatabase的管理朵锣。
[](javascript:void(0); "復(fù)制代碼")
<pre style="margin: 0px; white-space: pre-wrap; word-wrap: break-word; padding: 0px; list-style-type: none; list-style-image: none; font-family: "Courier New" !important; font-size: 12px !important;"> FMDatabaseQueue * queue = [FMDatabaseQueue databaseQueueWithPath:database_path];
dispatch_queue_t q1 = dispatch_queue_create("queue1", NULL);
dispatch_queue_t q2 = dispatch_queue_create("queue2", NULL);
dispatch_async(q1, ^{ for (int i = 0; i < 50; ++i) {
[queue inDatabase:^(FMDatabase *db2) {
NSString *insertSql1= [NSString stringWithFormat: @"INSERT INTO '%@' ('%@', '%@', '%@') VALUES (?, ?, ?)",
TABLENAME, NAME, AGE, ADDRESS];
NSString * name = [NSString stringWithFormat:@"jack %d", i];
NSString * age = [NSString stringWithFormat:@"%d", 10+i];
BOOL res = [db2 executeUpdate:insertSql1, name, age,@"濟南"]; if (!res) {
NSLog(@"error to inster data: %@", name);
} else {
NSLog(@"succ to inster data: %@", name);
}
}];
}
});
dispatch_async(q2, ^{ for (int i = 0; i < 50; ++i) {
[queue inDatabase:^(FMDatabase *db2) {
NSString *insertSql2= [NSString stringWithFormat: @"INSERT INTO '%@' ('%@', '%@', '%@') VALUES (?, ?, ?)",
TABLENAME, NAME, AGE, ADDRESS];
NSString * name = [NSString stringWithFormat:@"lilei %d", i];
NSString * age = [NSString stringWithFormat:@"%d", 10+i];
BOOL res = [db2 executeUpdate:insertSql2, name, age,@"北京"]; if (!res) {
NSLog(@"error to inster data: %@", name);
} else {
NSLog(@"succ to inster data: %@", name);
}
}];
}
}); </pre>
[](javascript:void(0); "復(fù)制代碼")
上面就是iOS中FMDB數(shù)據(jù)庫框架的一些基本應(yīng)用.