0.準備工作
github FMDB下載地址:https://github.com/ccgus/fmdb
拖拽fmdb文件到項目中、導入#import "FMDB.h"。必要時導入sqlite3.0系統庫
//添加FMDatabase屬性
@property (nonatomic, strong) FMDatabase *db;
1.打開數據庫并創建表
// 0.獲取沙盒地址
NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject];
NSString *sqlFilePath = [path stringByAppendingPathComponent:@"student.sqlite"];
// 1.加載數據庫對象
self.db = [FMDatabase databaseWithPath:sqlFilePath];
// 2.打開數據庫
if([self.db open])
{
NSLog(@"打開成功");
// 2.1創建表(在FMDB框架中, 增加/刪除/修改/創建/銷毀都統稱為更新)
BOOL success = [self.db executeUpdate:@"CREATE TABLE IF NOT EXISTS t_student (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, score REAL DEFAULT 1);"];
if (success) {
NSLog(@"創建表成功");
}else
{
NSLog(@"創建表失敗");
}
}else
{
NSLog(@"打開失敗");
}
2.增、刪、改
// FMDB中可以用?當作占位符, 但是需要注意: 如果使用問號占位符, 以后只能給占位符傳遞對象
BOOL success = [self.db executeUpdate:@"INSERT INTO t_student(score, name) VALUES (?, ?);", @(20), @"Jack"];
if (success) {
NSLog(@"插入成功");
}else
{
NSLog(@"插入失敗");
}
3.查詢,在這里可以進行數據轉模型
// FMDB框架中查詢用executeQuery方法
// FMResultSet結果集, 結果集其實和tablevivew很像
FMResultSet *set = [self.db executeQuery:@"SELECT id, name, score FROM t_student;"];
while ([set next]) { // next方法返回yes代表有數據可取
int ID = [set intForColumnIndex:0];
NSString *name = [set stringForColumnIndex:1];
double score = [set doubleForColumnIndex:2];
NSLog(@"%d %@ %.1f", ID, name, score);
}