一、之前使用数据库,由于通常就创建一张表,因此都是本身写代码建立,没用过fmdb,此次由于项目中涉及聊天模块,须要多张表格和数据库保存聊天记录git
按照之前方法很差操做,就研究了下fmdb,发现确实挺方便的。FMDB下载地址:https://github.com/ccgus/fmdb。github
二、导入FMDB文件,再导入libsqlite3.tbd依赖包。sql
//建立打开数据库
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秒。spa
>>>>> 其余比较详细的FMDB使用介绍。.net
=====> http://m.blog.csdn.net/article/details?id=7204625code
O(∩_∩)Oorm