如果你想打开一个 sqlite 数据库,你可能想:
确保将数据库包含在包中。
以编程方式将数据库从您的包复制到您的文档(如果用户要修改数据库,这尤其重要;如果您只是阅读,您可以继续打开包中的版本)。
如果你在你的模拟器中运行它,你可以继续检查 bundle 和 Documents 文件夹,如果事情不正确,只是为了确保一切都在它应该在的地方。您的模拟器文件夹类似于“~/Library/Application Support/iPhone Simulator/5.1/Applications/”(将 5.1 替换为您正在使用的模拟器的任何版本)。chflags nohidden ~/Library
您可能必须通过在Terminal
命令行窗口中运行来取消隐藏您的库文件夹(如果您还没有) 。
因此,获取数据库路径的代码(如果还没有,则将其复制到 Documents)可能如下所示:
NSString *databaseName = kDatabaseName; // obviously, replace this with your database filename, e.g., @"myExampleDatabase.db"
NSString *documentsFolder = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *databaseFullDocumentPath = [documentsFolder stringByAppendingPathComponent:databaseName];
NSString *databaseFullBundlePath = [[NSBundle mainBundle] pathForResource:databaseName ofType:@""];
NSFileManager *fileManager = [NSFileManager defaultManager];
if (![fileManager fileExistsAtPath:databaseFullDocumentPath])
{
NSAssert([fileManager fileExistsAtPath:databaseFullBundlePath], @"Database not found in bundle");
NSError *error;
if (![fileManager copyItemAtPath:databaseFullBundlePath toPath:databaseFullDocumentPath error:&error])
NSLog(@"Unable to copy database from '%@' to '%@': error = %@", databaseFullBundlePath, databaseFullDocumentPath, error);
}
然后,如果您正在执行自己的 sqlite 调用,它将类似于:
sqlite3 *database;
if (sqlite3_open_v2([databaseFullDocumentPath UTF8String], &database, SQLITE_OPEN_READWRITE, NULL) == SQLITE_OK)
{
// do whatever you want to do
}
或者,或者,如果您使用的是 FMDB,它将类似于:
FMDatabase *db = [[FMDatabase alloc] initWithPath:databaseFullDocumentPath];
NSAssert(db, @"Unable to open create FMDatabase");
BOOL success = [db open];
NSAssert(success, @"Unable to open database");
if (success)
{
// do whatever you want to do
}