无法在iOS中连接SQLite数据库
我是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);
但是当我使用上面的代码替换我的数据库名称时,我得到了后续alertview中指定的错误。
我的问题是,我是否必须将数据库文件添加到我的资源文件夹中? 如果没有,我是否必须将我的数据库文件放在iOS可以访问的地方?
我建议在SQLite中使用FMDB包装器: https : //github.com/ccgus/fmdb
如果要打开sqlite数据库,可能需要:
-
确保将数据库包含在捆绑包中。
-
以编程方式将数据库从您的软件包复制到您的文档(特别重要的是,如果用户将修改数据库;如果您只是阅读,您可以继续只打开软件包中的版本)。
-
如果你在你的模拟器中运行它,你可以继续检查bundle和Documents文件夹,如果事情不对,只是为了确保一切都在它应该的位置。 你模拟器的文件夹类似于“〜/ 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, eg, @"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 }
但是,在大多数情况下,我完全支持以前的答案:
您确定必须使用sqlite3
而不是Core Data
吗?
有几个讨论,您可以在何时使用数据库包装器(如fmdb )以及何时使用Core Data
获取信息。 (就个人而言,我喜欢使用fmdb,但它总是导致更多的代码,复杂性和大多数时候性能更差)
- 核心数据与SQLite 3
- 在iPhone上使用CoreData或SQLite?
- 核心数据与Sqlite和性能
- 核心数据与SQLite 3
- 是否值得使用iphone上的简单sqlite应用程序的核心数据与一个表,没有关系或复杂的子表/视图?
- Core Data与SQLite for SQL经验丰富的开发人员
一些链接可以开始使用Core Data
:
- 核心数据编程指南(Apple)
- 适用于iOS的核心数据教程(Apple)