基本介绍
SQLite (http://www.sqlite.org/docs.html) 是一个轻量级的关系数据库。原生的SQLite API在使用上相当不友好,在使用时,非常不便。于是,开源社区中就出现了一系列将SQLite API进行封装的库,而FMDB (https://github.com/ccgus/fmdb) 则是开源社区中的优秀者。手动导入FMDB需添加静态依赖libsqlite3.tbd。
1.设置保持路径,创建FMDB对象
NSString * path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
NSString * pathStr = [path stringByAppendingString:@"/test1.sqlite"];
_db = [FMDatabase databaseWithPath:pathStr];
if (![_db open]) {
NSLog(@"打开失败");
return;
}
NSLog(@"打开成功");
2.创建表单
NSString * sqlStr = @"CREATE TABLE IF NOT EXISTS searchRecord(id integer PRIMARY KEY AUTOINCREMENT,name text NOT NULL,age integer DEFAULT 20,sex text DEFAULT '女');";
if ([_db executeStatements:sqlStr]) {
NSLog(@"创建表成功");
}else{
NSLog(@"创建表失败");
}
3.插入数据
NSString * sqlStr = @"INSERT INTO searchRecord(name,sex,age) VALUES('小红','女',18);";
if ([_db executeUpdate:sqlStr]) {
NSLog(@"插入成功");
}else{
NSLog(@"插入失败");
}
4. 查询数据
NSString * sqlStr = @"SELECT * FROM searchRecord;";
NSArray * array = @[];
FMResultSet *s =[_db executeQuery:sqlStr withArgumentsInArray:array];
while ([s next]) {
NSString * name = [s objectForColumnName:@"name"];
NSInteger age = [s intForColumn:@"age"];
NSString * sex = [s objectForColumnName:@"sex"];
NSLog(@"%@", name );
NSLog(@"%ld", (long)age);
NSLog(@"%@", sex);
}
5.删除数据
NSString * sqlStr = @"DELETE FROM searchRecord;";
if ([_db executeUpdate:sqlStr]) {
NSLog(@"删除成功");
}else{
NSLog(@"删除失败");
}
6.修改数据
NSString * sqlStr = @"UPDATE searchRecord SET age=20 WHERE age=18;";
if ([_db executeUpdate:sqlStr]) {
NSLog(@"修改成功");
}else{
NSLog(@"修改失败");
}
7.FMDB线程安全
这里就不做过多介绍可以参考博客http://blog.csdn.net/kingkong1024/article/details/7744285