- (void)copyDBFile
{
NSFileManager *manager = [NSFileManager defaultManager];
//如果檔案存在,就不複製
if ([manager fileExistsAtPath:[self databasePath]]) {
return;
}
NSString *atPath = [[NSBundle mainBundle] pathForResource:kDatabaseName ofType:nil];
//複製資料庫檔案到沙箱路徑下
[manager copyItemAtPath:atPath toPath:[self databasePath] error:nil];
}
//取得資料庫檔案所在的路徑
- (NSString *)databasePath
{
// NSLog(@"%@", [[NSBundle mainBundle] pathForResource:kDatabaseName ofType:nil]);
return [NSHomeDirectory() stringByAppendingFormat:@"/Library/%@", kDatabaseName];
// return [[NSBundle mainBundle] pathForResource:kDatabaseName ofType:nil];
}
//增加一條資料
- (BOOL)addUser:(User *)user
{
//資料庫物件
sqlite3 *mysqlite = nil;
//1.開啟資料庫
//filename:資料庫檔案的路徑(C的字串)
//sqlite3:具體執行的資料庫物件
int openResult = sqlite3_open([[self databasePath] UTF8String], &mysqlite);
//如果open函數執行成功,會返回0,SQLITE_OK
if (openResult != SQLITE_OK) {
NSLog(@"資料庫開啟失敗");
return NO;
}
//2.準備SQL語句
//可以把 sqlite3_stmt * 所儲存的內容看成是 sql語句
sqlite3_stmt *stmt = nil;
//構造sql語句
NSString *sql = [NSString stringWithFormat:@"insert into UserTable (username, password, phone, age) values (\"%@\", \"%@\", \"%@\", %ld)", user.username, user.password, user.phone, user.age];
//sqlite3:具體執行的資料庫物件
//zSql: sql語句
//stmt: 語句儲存的對象
sqlite3_prepare(mysqlite, [sql UTF8String], -1, &stmt, NULL);
//3.執行SQL語句
int stepResult = sqlite3_step(stmt);
if (stepResult == SQLITE_ERROR || stepResult == SQLITE_MISUSE) {
NSLog(@"執行失敗");
}
//4.SQL語句完結
sqlite3_finalize(stmt);
//5.關閉資料庫
sqlite3_close(mysqlite);
return YES;
}
4.CoreData
- (void)openDataBase
{
//1.載入資料模型檔案 xcdatamodeld
NSURL *url = [[NSBundle mainBundle] URLForResource:@"DataModel" withExtension:@"momd"];
//NSManagedObjectModel 用於載入資料模型檔案
NSManagedObjectModel *dataModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:url];
//2.開啟模型檔案對應的資料庫檔案
//建立協調器對象,使用協調器管理資料庫檔案
NSPersistentStoreCoordinator *psc = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:dataModel];
//指定資料庫檔案在沙箱中的位置
NSString *storePath = [NSHomeDirectory() stringByAppendingString:@"/Documents/DataStore.sqlite"];
NSURL *storeURL = [NSURL fileURLWithPath:storePath];
//開啟一個資料檔案 PersistentStore --> 資料庫檔案
/*
1.如果檔案不存在,建立新的資料庫檔案
2.如果檔案存在,直接開啟這個檔案
*/
NSError *error = nil;
[psc addPersistentStoreWithType:NSSQLiteStoreType //產生的資料庫檔案格式為SQLite
configuration:nil
URL:storeURL //資料庫檔案儲存的路徑
options:nil
error:&error];
if (error) {
NSLog(@"資料庫檔案開啟失敗");
} else
{
NSLog(@"資料庫開啟成功");
}
//3.操作資料庫
context = [[NSManagedObjectContext alloc] init];
//指定context使用哪一個coordinator來操作資料庫檔案
context.persistentStoreCoordinator = psc;
}