//创建数据库中的表
BOOL stuSql = [db executeUpdate:@"create table if not exists stu(stuid integer primary key autoincrement, name varchar(255),sex varchar(255),age integer)"];
//向数据库中插入数据
NSString *insertSql = @"insert into stu(stuid,name,sex,age) values(?,?,?,?)";
BOOL success = [db executeUpdate:insertSql,@"1",[NSString stringWithFormat:@"zxm"],@"男",@20];
//查询数据库 //查询所有的数据库数据
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"]);
}
//通过某个字段检查是否存在数据
NSString * querySql = [NSString stringWithFormat:@"select * from stu where %@='%@'", table,@"男",@20];
//清空数据库
NSString *deleteSql = @"delete from stu";
BOOL success = [db executeUpdate:deleteSql];
//修改数据库中的数据 //tian6是新值 代替数据库中name = tian1的值
NSString *updateSql = @"update stu set name = ? where name = ?";
BOOL success = [db executeUpdate:updateSql,@"tian6",@"tian1"];
iOS中原声的SQLite API在进行数据存储的时候,需要使用C语言中的函数,操作比较麻烦,于是就出现了一系列将SQLite封装的库。本文讲解的FMDB就是其中的一个。
FMDB PK Sqlite
优点:
1.对多线程的并发操作进行了处理,所以是线程安全的
2.以OC的方式封装了SQLite的C语言API,使用起来更加方便
3.FMDB是轻量级框架 使用灵活
缺点:
因为它是OC的语言封装的,只能在ios开发的时候使用,所以在实现跨平台操作的时候存在局限性。
FMDB框架中重要的框架类
FMDataBase
FMDataBase对象就代表一个单独的SQLite数据库 用来执行SQL语句
FMResultSet
使用FNDataBase执行查询后的结果集
FMDataBaseQueue
用于在多线程中执行多个查询或更新 他是线程安全的
下面通过一个例子来讲解FMDB的具体用法
首先使用FMDB需要导入libsqlite3.0框架,在需要数据库的类中引入
FMDatabase.h.``
创建数据库
例子中用到的测试模型类
[ 复制代码](javascript:void(0); "复制代码")
<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); "复制代码")
创建数据库的代码
[ 复制代码](javascript:void(0); "复制代码")
<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 { //创建数据库 //1>获取数据库文件的路径
NSString *docpath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *fileName = [docpath stringByAppendingPathComponent:@"student.sqlite"]; //初始化数据库
db = [[FMDatabase alloc] initWithPath:fileName]; //创建数据库中的表
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(@"数据库创建表成功");
}else {
NSLog(@"创建表失败");
}
}else {
NSLog(@"数据库没有打开");
}
}else {
NSLog(@"创建数据库失败");
}
}</pre>
](javascript:void(0); "复制代码")
注意创建数据库时路径的问题 路径可以是以下三种方式之一
1.文件路径 该文件路径真实存在,如果不存在回自动创建
2.空字符串@"" 表示会在临时目录里创建一个空的数据库 当FMDataBase连接关闭时 文件也会被删除
3.NULL 将创建一个内在数据库 同样的 当FMDataBase连接关闭时 数据将会被销毁
向数据库中添加数据 查找数据 和 删除数据
[ 复制代码](javascript:void(0); "复制代码")
<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)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(@"数据插入成功"); }
}
} //查询数据库 //查询所有的数据库数据 -
(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"]);
}
} //清空数据库
- (void)deleteAllDbData {
NSString *deleteSql = @"delete from stu";
BOOL success = [db executeUpdate:deleteSql]; if (success) {
NSLog(@"删除数据成功");
}
}</pre>
[[图片上传失败...(image-15801f-1529369304986)]](javascript:void(0); "复制代码")
清空数据库之前的打印结果是
[ 复制代码](javascript:void(0); "复制代码")
<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] 数据插入成功
FMDB[1530:98012] 数据插入成功
FMDB[1530:98012] 数据插入成功
FMDB[1530:98012] 数据插入成功
FMDB[1530:98012] 数据插入成功
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); "复制代码")
修改数据
[ 复制代码](javascript:void(0); "复制代码")
<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)updateDbData { //tian6是新值 代替数据库中name = tian1的值
NSString *updateSql = @"update stu set name = ? where name = ?";
BOOL success = [db executeUpdate:updateSql,@"tian6",@"tian1"]; if (success) {
[self selectDataFormDb];
}
} //结果
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); "复制代码")
下面是另写的一个完整的例子
student.h文件
[ 复制代码](javascript:void(0); "复制代码")
<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); "复制代码")
studentManager.h文件
[ 复制代码](javascript:void(0); "复制代码")
<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; //添加一条数据到数据表中
-(BOOL)addDataWithModel:(Student*)student ConditionString:(NSString *)conditionStr andconditionValue:(NSString *)conditionValue andtable:(NSString * )table; //通过某个字段删除一条数据;
-(BOOL)deleteDataWithConditionString:(NSString *)conditionStr andconditionValue:(NSString *)conditionValue andtable:(NSString * )table; // 删除所有的记录
- (BOOL)deleteAllDataWithtable:(NSString )table; //查询一条数据; //1.查询全部数据,2根据特定字段查询数据;
-(NSArray * )getDataWithconditionString:(NSString * )conditionstr andConditionValue:(NSString )conditionValue allData:(BOOL)isAllData andTable:(NSString )table; //修改某条数据
-(BOOL)updateDataWithString:(NSString)NewStr andNewStrValue:(id)NewStrValue andConditionStr:(NSString)conditionStr andConditionValue:(NSString)conditionValue andTable:(NSString*)table; @end</pre>
](javascript:void(0); "复制代码")
studentManager.m文件
[ 复制代码](javascript:void(0); "复制代码")
<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]) { // 创建数据库,使用FMDB第三方框架 // 创建数据库文件保存路径..../Documents/app.sqlite // sqlite数据库(轻量级的数据库),它就是一个普通的文件,txt是一样的,只不过其中的文件内容不一样。 // 注:sqlite文件中定义了你的数据库表、数据内容 // MySql、Oracle这些大型的数据库,它需要一个管理服务,是一整套的。
NSString * dbPath=[NSString stringWithFormat:@"%@/Documents/app.sqlite",NSHomeDirectory()];
NSLog(@"%@",dbPath); // 创建FMDatabase // 如果在目录下没有这个数据库文件,将创建该文件。
_database=[[FMDatabase alloc]initWithPath:dbPath]; if (_database) { if ([_database open]) { //第一步:创建学生信息表
NSString *stuSql = @"create table if not exists stu(stuid varchar(255),name varchar(255),age varchar(255),headimage binary)"; //第一步:创建学生信息表
NSString * createSql=@"create table if not exists stu(stuid varchar(255),name varchar(255),age varchar(255),headimage binary)"; // FMDatabase执行sql语句 // 当数据库文件创建完成时,首先创建数据表,如果没有这个表,就去创建,有了就不创建
BOOL creatableSucess=[_database executeUpdate:createSql];
NSLog(@"创建表%d",creatableSucess);
} else {
NSLog(@"打开数据库失败");
}
} else {
NSLog(@"创建数据库失败");
}
} return self;
} ////通过某个字段检查是否存在数据
-
(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]; // 判断是否已存在数据
if ([set next]) { return YES;
} else
return NO;
} //添加一条数据到数据表中
-(BOOL)addDataWithModel:(Student*)student ConditionString:(NSString *)conditionStr andconditionValue:(NSString *)conditionValue andtable:(NSString * )table
{ // 如果已存在数据,先删除已有的数据,再添加新数据
BOOL isExsits = [self isExsitsWithConditionString:conditionStr andConditionValue:conditionValue andtable:table]; if (isExsits) {
[self deleteDataWithConditionString:conditionStr andconditionValue:conditionValue andtable:table];
} // 添加新数据
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;
} //通过某个字段删除一条数据;
-(BOOL)deleteDataWithConditionString:(NSString *)conditionStr andconditionValue:(NSString *)conditionValue andtable:(NSString * )table
{ //删除之前先判断该数据是否存在;
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;
} //查询一条数据; //1.查询全部数据,2根据特定字段查询数据;
-(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];
} // 执行sql
FMResultSet * set = [_database executeQuery:getSql]; // 循环遍历取出数据
NSMutableArray * array = [[NSMutableArray alloc] init]; while ([set next]) {
Student * model = [[Student alloc] init]; // 从结果集中获取数据 // 注:sqlite数据库不区别分大小写
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;
} //修改某条数据
-(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); "复制代码")
数据库的多线程操作
如果应用中使用了多线程操作数据库,那么就需要使用FMDatabaseQueue来保证线程安全了。 应用中不可在多个线程中共同使用一个FMDatabase对象操作数据库,这样会引起数据库数据混乱。 为了多线程操作数据库安全,FMDB使用了FMDatabaseQueue,使用FMDatabaseQueue很简单,首先用一个数据库文件地址来初使化FMDatabaseQueue,然后就可以将一个闭包(block)传入inDatabase方法中。 在闭包中操作数据库,而不直接参与FMDatabase的管理。
[ 复制代码](javascript:void(0); "复制代码")
<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); "复制代码")
上面就是iOS中FMDB数据库框架的一些基本应用.
网友评论