FMDB是对sqlite进行封装的第三方库,对于其基础的知识网络中已经有了数不胜数的说明,这里就不在重复的说明。本文的主要目的是了解FMDB的基本操作:
1)通过手动或cocopads添加FMDB的第三方库。
2)在工程中添加头文件:
#import <FMDatabaseAdditions.h>
#import <FMDatabaseQueue.h>
补:本案例只有有user一个表 表中有列三个:姓名,年龄,性别。
*路径
- (NSString *)databasePath
{
NSString *path =[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES)objectAtIndex:0];
NSString *dbPath = [pathstringByAppendingPathComponent:@"user.db"];
return dbPath;
}
3) 插入
FMDatabase *database = [FMDatabasedatabaseWithPath:[selfdatabasePath]]; //根据路径找到数据库,如果不存在则自动创建一个
if (![database open]) { //判断数据库是否打开
NSLog(@"open database failed");
return;
}
if (![databasetableExists:@"user"]) { //判断是否存在表user,如果不存在就创建表
[database executeUpdate:@"create table user (id integer primary key autoincrement not null,name text,age text,sex text)"];
}
BOOL insert = [databaseexecuteUpdate:@"insert into user(name,age,sex) values (?,?,?)",_name.text,_age.text,_sex.text];//通过sql语句来进行操作
if (insert) {
NSLog(@"保存成功");
}else
{
NSLog(@"保存失败");
}
[database close];
4) 删除
FMDatabase *database = [FMDatabasedatabaseWithPath:[selfdatabasePath]];
if (![databaseopen]) {
return;
}
BOOL delete = [databaseexecuteUpdate:@"delete from user where name = ?",@""];
if (delete) {
NSLog(@"删除成功");
}else
{
NSLog(@"删除失败");
}
[database close];
5) 更新
FMDatabase* database=[FMDatabase databaseWithPath:[self databasePath]];
if (![database open]) {
return;
}
BOOL update=[database executeUpdate:@"update user set age = ? where name= ?",@"20",@"chen"];
if (update) {
NSLog(@"更新成功");
}else {
NSLog(@"更新失败");
}
[database close];
6) 查询
FMDatabase *database = [FMDatabase databaseWithPath:[self databasePath]];
if (![database open]) {
return;
}
FMResultSet *result = [database executeQuery:@"select *from user"];
while ([result next]) {
NSString *name = [result stringForColumn:@"name"];
NSLog(@"name = %@",name);
}
[database close];