1,拿到資料庫檔案的路徑self.path = NSHomeDirectory();self.path = [path stringByAppendingPathComponent:@"Documents/data.db"];2,拿到資料庫物件,開啟資料庫,如果這個資料庫不存在,就會自動建立FMDatabase* db = [FMDatabase databaseWithPath:path]; BOOL res = [db open]; if (res == NO) { NSLog(@"開啟失敗"); return; }else{ NSLog(@"資料庫開啟成功"); }3,//如果表不存在,建立 res = [db executeUpdate:@"create table if not exists Students(name,score,image)"];//執行sql語句 if (res == NO) { NSLog(@"建立失敗"); [db close];//關閉資料庫 return; }else if(res==YES){ NSLog(@"建立成功"); }4,表建立成功之後,就進行增刪改查的操作: 1>,插入資料 res = [db executeUpdate:@"insert into Students values (?,?,?)", name, num, headData]; if (res == NO) { NSLog(@"插入失敗"); } [db close]; 2>,刪除操作:- (void)del:(id)sender{ FMDatabase* db = [FMDatabase databaseWithPath:path]; //開啟資料庫 BOOL res = [db open]; //如果失敗,退出方法 if (res == NO) { NSLog(@"開啟失敗"); return; } //刪除 res = [db executeUpdate:@"delete from Students where name=?",nameField.text]; if (res == NO) { NSLog(@"刪除失敗"); } [db close];} 3>,更新操作:- (void)update:(id)sender{ FMDatabase* db = [FMDatabase databaseWithPath:path]; BOOL res = [db open]; if (res == NO) { NSLog(@"開啟失敗"); return; } NSNumber* num = [NSNumber numberWithInt:[scoreField.text intValue]]; res = [db executeUpdate:@"update Students set score=? where name=?", num, nameField.text]; if (res == NO) { NSLog(@"修改失敗"); } [db close];} 4>,查詢操作:- (void)fetch:(id)sender{ FMDatabase* db = [FMDatabase databaseWithPath:path]; BOOL res = [db open]; if (res == NO) { NSLog(@"開啟失敗"); return; } FMResultSet* set = [db executeQuery:@"select * from Students"];//FMResultSet相當於遊標集 //建立數組,儲存所有學生資訊 NSMutableArray* array = [NSMutableArray arrayWithCapacity:0]; //遍曆Students表 while ([set next]) {//有下一個的話,就取出它的資料,然後關閉資料庫 //姓名 NSString* name = [set stringForColumn:@"name"]; //成績 int score = [set intForColumnIndex:1]; //照片 NSData* data = [set dataForColumnIndex:2]; //float a = [[set objectForColumnIndex:3] floatValue]; UIImage* image = [UIImage imageWithData:data]; StudentItem* student = [[StudentItem alloc] init]; student.name = name; student.score = score; student.image = image; [array addObject:student]; [student release]; } [db close]; }