2

我对 SQLite 和 iOS 完全陌生。我正在关注如何在 iOS 中使用 SQLite 的基本教程:

http://www.switchonthecode.com/tutorials/using-sqlite-on-the-iphone#comment-11617

在上面的链接中,他们将数据库指定为:

sqlite3 *database;

int result = sqlite3_open("/myExampleDatabase.db", &database);

但是当我使用上面的代码替换我的数据库名称时,我收到了后续警报视图中指定的错误。

我的问题是,我是否必须将数据库文件添加到我的资源文件夹中?如果没有,我是否必须将我的数据库文件放在 iOS 可以访问的地方?

4

3 回答 3

6

我建议对 SQLite 使用 FMDB 包装器: https ://github.com/ccgus/fmdb

于 2012-07-26T07:22:43.953 回答
4

如果你想打开一个 sqlite 数据库,你可能想:

  1. 确保将数据库包含在包中。

  2. 以编程方式将数据库从您的包复制到您的文档(如果用户要修改数据库,这尤其重要;如果您只是阅读,您可以继续打开包中的版本)。

  3. 如果你在你的模拟器中运行它,你可以继续检查 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
}
于 2012-07-26T17:27:38.230 回答
0

在大多数情况下,我完全支持前面的答案,但是:

你确定你必须使用sqlite3而不是Core Data

有几个讨论可以让您了解何时使用数据库包装器(如fmdb)以及何时使用Core Data. (就个人而言,我喜欢使用 fmdb,但它总是会导致更多的代码、复杂性和大多数时候性能更差)

一些开始使用的链接Core Data

于 2012-07-26T13:09:24.237 回答