1.打开数据库

#import "ViewController.h"
#import "FMDB.h" @interface ViewController () @property (nonatomic, strong) FMDatabase *db; @end @implementation ViewController - (void)viewDidLoad {
[super viewDidLoad]; //打开数据库
[self dbOpen]; } /**
* 打开数据库
*/
-(void)dbOpen
{
//1.获取数据库文件的路径
NSString *doc=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject]; NSString *fileName=[doc stringByAppendingPathComponent:@"toothGroup.sqlite"]; NSLog(@"%@",fileName); //2.获得数据库
FMDatabase *db=[FMDatabase databaseWithPath:fileName]; //3.打开数据库
if ([db open]) { //创建表的时候必须要有一个integer类型的,否则创建不成功 NSString *create=@"create table if not exists t_group11(id integer primary key autoincrement,filename text NOT NULL,title text NOT NULL,price text NOT NULL,endTime text NOT NULL)"; BOOL result=[db executeUpdate:create]; if (result) {
NSLog(@"创表成功");
}
else
{
NSLog(@"创表失败");
} } self.db=db;
}

2.插入数据

  //往数据库插入数据 缓存数据
if ([self.db open]) { NSString *sql=[NSString stringWithFormat: @"INSERT INTO t_group11 (filename,title,price,endTime) VALUES('%@','%@','%@','%@')",dict[@"filename"],dict[@"title"],dict[@"price"],dict[@"endTime"]]; BOOL result=[self.db executeUpdate:sql]; if (result) {
NSLog(@"插入成功");
}
else
{
NSLog(@"插入失败");
} }

3.查询数据

 // 1.执行查询语句
FMResultSet *resultSet = [self.db executeQuery:@"SELECT * FROM t_group11"]; // 2.遍历结果
while ([resultSet next]) {
int ID = [resultSet intForColumn:@"id"]; NSString *filename=[resultSet stringForColumn:@"filename"];
NSString *title=[resultSet stringForColumn:@"title"];
NSString *price=[resultSet stringForColumn:@"price"];
NSString *endTime=[resultSet stringForColumn:@"endTime"]; NSLog(@"%d %@ %@ %@ %@", ID, filename, title,price,endTime);
}

4.删除数据,表

 //删除表
[self.db executeUpdate:@"DROP TABLE IF EXISTS t_group11"];
05-11 13:24