1.打開資料庫 #import "ViewController.h" #import "FMDB.h" @interface ViewController () @property (nonatomic, strong) FMDatabase *db; @end @implementation Vi ...
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; }View Code
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(@"插入失敗"); } }View Code
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); }View Code
4.刪除數據,表
//刪除表 [self.db executeUpdate:@"DROP TABLE IF EXISTS t_group11"];View Code