- (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;
}