1、以前使用数据库,因为一般就建立一张表,所以都是自己写代码创建,没用过fmdb,这次因为项目中涉及聊天模块,需要多张表格和数据库保存聊天记录
按照以前方法不好操作,就研究了下fmdb,发现确实挺方便的。FMDB下载地址:https://github.com/ccgus/fmdb。
2、导入FMDB文件,再导入libsqlite3.tbd依赖包。
//创建打开数据库
NSString *path = [self getDBPath:@"student"];//如果名称为空 数据库断开时会删除
DDb = [FMDatabase databaseWithPath:path];
[self createTable:@"95230"]; //建表
[self insertDate:@"95230"]; //添加数据
[self updataWithTable:@"95230"]; //修改
[self deledataWith:@"95230"]; //删除
[self chaxunWith:@"95230"]; //查询
NSLog(@"%@/Documents",NSHomeDirectory()); //模拟器运行时 打开Documents查看数据库文件
//查询数据库
-(void)chaxunWith:(NSString *)tabname
{
if ([DDb open]) {
// NSString *sql = [NSString stringWithFormat:@"select * from '%@' where age = '%@'",tabname,@"18"];//
NSString *sql = [NSString stringWithFormat:@"select * from '%@'",tabname];
FMResultSet * rs = [DDb executeQuery:sql];
while ([rs next]) {
NSString * name = [rs stringForColumn:@"name"];
int age = [rs intForColumn:@"age"];
NSData *imgdata = [rs dataForColumn:@"image"];
NSLog(@"%@ - %i",name,age);
}
[DDb close];
}
}
//删除数据
-(void)deledataWith:(NSString *)tabname
{
if ([DDb open]) {
NSString *sql = [NSString stringWithFormat:@"delete from '%@' where %@ = '%@'",tabname,@"age",@"19"];
BOOL dele = [DDb executeUpdate:sql];
if (!dele) {
NSLog(@"delete fail");
}
[DDb close];
}
}
//修改数据
-(void)updataWithTable:(NSString *)tabname
{
if ([DDb open]) {
NSString *sql = [NSString stringWithFormat:@"update '%@' set %@ = '%@' where age = '%@'",tabname,@"name",@"张86",@"18"];
BOOL update =[DDb executeUpdate:sql];
if (!update) {
NSLog(@"update fail");
}
[DDb close];
}
}
//添加数据
-(void)insertDate:(NSString *)tabname
{
if ([DDb open])
{
NSString *bb = [NSString stringWithFormat:@"INSERT INTO '%@' (name, age, image) VALUES (?,?,?)",tabname];
// UIImage *img = [UIImage imageNamed:@"test"];
// NSData *imgdata = UIImagePNGRepresentation(img);
BOOL insert = [DDb executeUpdate:bb,@"小三",@"20",[NSData data]];
if (!insert) {
NSLog(@"insert fail");
}
[DDb close];
}
}
//创建数据库表格
-(void)createTable:(NSString *)tabname
{
if ([DDb open]) {
//判断表名是否为纯数字
NSString *sqlCreateTable = [NSString stringWithFormat:@"create table if not exists '%@' (id INTEGER PRIMARY KEY AUTOINCREMENT, name text,age integer, image blob)",tabname]; BOOL res = [DDb executeUpdate:sqlCreateTable];
if (!res) {
NSLog(@"创建表格失败");
}
[DDb close];
}
}
//创建数据库
-(NSString *)getDBPath:(NSString *)curname
{
curname = [NSString stringWithFormat:@"%@.sqlite",curname];
NSString *documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *DBPath = [documentPath stringByAppendingPathComponent:curname];
return DBPath;
}
注:FMDB写入图片数据NSData时候,图片转换成数据流用 UIImageJPEGRepresentation( img , float); 如果用 UIImagePNGRepresentation转的话,写入数据库时间会变长,
我5张图片没有压缩转 写入数据库时间需要花费1.5秒,而且是写入任何一个参数都要1.5秒。
>>>>> 其他比较详细的FMDB使用介绍。
=====> http://m.blog.csdn.net/article/details?id=7204625
O(∩_∩)O