如果你想打开一个 sqlite 数据库,你可能想:
确保将数据库包含在包中。
以编程方式将数据库从您的包复制到您的文档(如果用户要修改数据库,这尤其重要;如果您只是阅读,您可以继续打开包中的版本)。
如果您在模拟器中运行此程序,您可以继续检查捆绑包和文档文件夹(如果事情不正常),以确保一切都在应有的位置。您的模拟器文件夹类似于“~/Library/Application Support/iPhone Simulator/5.1/Applications/”(将 5.1 替换为您正在使用的模拟器的任何版本)。您可能需要通过在Terminal 命令行窗口中运行chflags nohidden ~/Library 来取消隐藏您的Library 文件夹。
因此,获取数据库路径的代码(如果还没有,则将其复制到 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
}