标签:
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使用介绍。
O(∩_∩)O
标签:
原文地址:http://www.cnblogs.com/qq95230/p/5814697.html