熟悉基本语法别看这篇文章了
我这里就是单纯记录下使用,备忘
1、导入包
2、github或者pod框架:FMDB
3、在相应界面,导入头文件开始使用
4、创建表
// 1.获得数据库文件的路径
NSString *doc =[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
// 2.拼接文件名
NSString *filename = [doc stringByAppendingPathComponent:@"wangyi.sqlite"];
// 3.得到数据库
FMDatabase *db = [FMDatabase databaseWithPath:filename];
NSLog(@"filename === %@",filename);
// 4.打开数据库
if ([db open]) {
// 5.创表
BOOL result = [db executeUpdate:@"CREATE TABLE IF NOT EXISTS test_tab (id integer PRIMARY KEY AUTOINCREMENT, name Text NOT NULL, age Text NOT NULL);"];
if (result) {
NSLog(@"成功创表");
} else {
NSLog(@"创表失败");
}
}else{
NSLog(@"打开表失败");
}
5、插入数据
// 1.获得数据库文件的路径
NSString *doc =[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
// 2.拼接文件名
NSString *filename = [doc stringByAppendingPathComponent:@"wangyi.sqlite"];
// 3.得到数据库
FMDatabase *db = [FMDatabase databaseWithPath:filename];
NSLog(@"filename === %@",filename);
// 4.打开数据库
if ([db open]) {
// 2.执行更新
for (int i = 0; i<50; i++) {
[db executeUpdate:@"insert into test_tab (name,age) values(?,?)",@"jack",@"21"];
}
NSLog(@"插入完成");
}else{
NSLog(@"打开表失败");
}
6、查询数据表,显示在tableView
[self.dataArray removeAllObjects];
// 1.获得数据库文件的路径
NSString *doc =[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
// 2.拼接文件名
NSString *filename = [doc stringByAppendingPathComponent:@"wangyi.sqlite"];
// 3.得到数据库
FMDatabase *db = [FMDatabase databaseWithPath:filename];
NSLog(@"filename === %@",filename);
// 4.打开数据库
if ([db open]) {
NSLog(@"打开表成功");
// 2.执行更新
FMResultSet *data = [db executeQuery:@"SELECT * FROM WYWork_tab ORDER BY id DESC"];
NSMutableArray *tempArray = [NSMutableArray array];
while ([data next]) {
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
// 每条记录的检索值
NSString *name = [data stringForColumn:@"name"];
NSString *time = [data stringForColumn:@"time"];
NSInteger ID = [data intForColumn:@"id"];
[dict setValue:name forKey:@"name"];
[dict setValue:time forKey:@"time"];
[dict setValue:@(ID) forKey:@"id"];
[tempArray addObject:dict];
}
NSLog(@"tempArray == %@",tempArray);
self.dataArray = [WYShowModel mj_objectArrayWithKeyValuesArray:tempArray];
}else{
NSLog(@"打开表失败");
}
//插入数据后,关闭数据库
[db close];
[self.tableView reloadData];
7、删除数据库条目
// 1.获得数据库文件的路径
NSString *doc =[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
// 2.拼接文件名
NSString *filename = [doc stringByAppendingPathComponent:@"wangyi.sqlite"];
// 3.得到数据库
FMDatabase *db = [FMDatabase databaseWithPath:filename];
NSLog(@"filename === %@",filename);
// 4.打开数据库
if ([db open]) {
NSLog(@"打开表成功");
//删除某条数据
NSString *deleteSql = [NSString stringWithFormat:@"delete from WYWork_tab where id = %ld",(long)index];
[db executeUpdate:deleteSql];
}else{
NSLog(@"打开表失败");
}
//插入数据后,关闭数据库
[db close];