【发布时间】:2013-06-19 15:13:35
【问题描述】:
更多 SQLite 问题。所以我的界面如下(这都是.m):
@interface Search()
@property (strong, nonatomic) NSString *databasePath; //path to sqlite database file
@property (strong, nonatomic) NSString *databaseName;
@property (nonatomic) sqlite3 *database;
@end
初始化如下:
- (id)init
{
if ((self = [super init]))
{
self.databaseName = DB_NAME;
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [documentPaths objectAtIndex:0];
_databasePath = [documentsDir stringByAppendingPathComponent:self.databaseName];
[self checkAndCreateDatabase];
if (sqlite3_open_v2([self.databasePath UTF8String], &_database, SQLITE_OPEN_READWRITE, NULL) != SQLITE_OK)
{
[[[UIAlertView alloc]initWithTitle:@"Missing"
message:@"Database file not found"
delegate:nil
cancelButtonTitle:@"OK"
otherButtonTitles:nil, nil]show];
}
else
{
NSLog(@"%s: sqlite3_open_v2 error: %s", __FUNCTION__, sqlite3_errmsg(self.database));
}
}
在init中Log返回的错误是:sqlite3_open_v2 error: not an error。在我的搜索中,我听说 SQLite 在指向不存在的数据库时不会返回错误。但我不确定为什么数据库不存在。我正在使用的复制功能(我之前得到并且似乎可以工作)如下:
-(void) checkAndCreateDatabase
{
// Check if the SQL database has already been saved to the users phone, if not then copy it over
BOOL dbExists;
// Create a FileManager object, we will use this to check the status
// of the database and to copy it over if required
NSFileManager *fileManager = [NSFileManager defaultManager];
// Check if the database has already been created in the users filesystem
dbExists = [fileManager fileExistsAtPath:_databasePath];
// If the database already exists then return without doing anything
if(dbExists)
{
return;
}
// If not then proceed to copy the database from the application to the users filesystem
// Get the path to the database in the application package
NSString *databasePathFromApp = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:_databaseName];
// Copy the database from the package to the users filesystem
//[fileManager copyItemAtPath:databasePathFromApp toPath:_databasePath error:nil];
NSError *error = nil;
if (![fileManager copyItemAtPath:databasePathFromApp toPath:_databasePath error:&error])
{
NSLog(@"%s: copyItemAtPathError: %@", __FUNCTION__, error);
}
}
最后,我在 iOS Simulator Documents 目录中验证了该数据库存在,并且我尝试对其执行的查询有效。为什么我会收到此错误?
【问题讨论】:
-
如果您正在使用大量 SQLite 交互,请考虑一下,然后选择 FMDB Framework。它非常轻巧、简单、干净。
-
在我阅读更多内容之前,它是否允许 SQL 查询?我正在从 Android 移植一个项目,并且已经编写了查询。
-
100% 可以工作。而且它只是 Objective-C SQLite 包装器。所以没有问题。
-
请参考您的question 如果有效请接受。
-
这可能是完美的。我不喜欢直接使用 SQLite 库,但我不想花时间编写自己的库。我想我应该只找一个。
标签: ios objective-c database sqlite