【问题标题】:Connect to bundled database with FMDB使用 FMDB 连接到捆绑的数据库
【发布时间】:2018-09-08 07:02:19
【问题描述】:

我通过

向我的捆绑包中添加了一个SQLite 数据库
  • 拖放到 XCode 中
  • 创建群组
  • 添加到目标(项目名称)

然后我尝试访问数据库

NSString *path = [[NSBundle mainBundle] pathForResource:@"test" ofType:@"mbtiles"];
NSLog(@"%@", path);

/Users/.../Library/Developer/CoreSimulator/Devices/4AB0090D-6035-4C78-90F3-CD6B70D81F05/data/Containers/Bundle/Application/721198C0-FFD8-42B1-9C79-78DBC54AB644/maps.app/测试.mbtiles

FMDatabase *db = [FMDatabase databaseWithPath:path];
[db open];
FMResultSet *rs = [db executeQuery:@"SELECT * FROM maps"];

到目前为止,一切似乎都很好。至少我没有收到任何错误/警告。

NSLog(@"%@", rs); 

FMResultSet: 0x604000a5f380

NSDictionary *dict = [rs resultDictionary];
NSLog(@"%@", dict);

警告:此集中似乎没有列。

NSData *tile = [databaseResult dataForColumn:@"tile_data"];

(空)

这是为什么呢?是否无法访问保存在捆绑资源中的数据库?

我尝试使用 code 检查数据库是否存在

BOOL success;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *appDBPath = [documentsDirectory stringByAppendingPathComponent:@"test.mbtiles"];
success = [fileManager fileExistsAtPath:appDBPath];
NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"test.mbtiles"];
success = [fileManager copyItemAtPath:defaultDBPath toPath:appDBPath error:&error];

打开 /Users/.../Library/Developer/CoreSimulator/Devices/4AB0090D-6035-4C78-90F3-CD6B70D81F05/data/Containers/Data/Application/EB9390A7-2210-4C8A-A94A-016C03FA1296/Documents/ test.mbtiles: 文件存在

这告诉我database 如果我没记错的话就在那里?! 但是,当我尝试类似

NSAssert(success, @"Failed to create writable database file with message '%@'.", [error localizedDescription]);

*** -[DatabaseAccess loadTileAtPath:result:], /Users/.../DatabaseAccess.m:78 中的断言失败

我有点迷路了。为什么我无法查询我的database

【问题讨论】:

  • 你勾选了副本吗?

标签: ios objective-c xcode sqlite fmdb


【解决方案1】:

即使人们只期望有 one 行的结果,也需要 next 语句。

FMResultSet *s = [db executeQuery:@"SELECT * FROM myTable"];
while ([s next]) {
    //retrieve values for each record
}

在尝试访问查询中返回的值之前,您必须始终调用-[FMResultSet next],即使您只期望一个:

FMResultSet *s = [db executeQuery:@"SELECT COUNT(*) FROM myTable"];
if ([s next]) {
    int totalCount = [s intForColumnIndex:0];
}

来源:https://github.com/ccgus/fmdb#executing-queries

【讨论】:

    猜你喜欢
    • 2011-05-19
    • 1970-01-01
    • 2012-09-18
    • 1970-01-01
    • 1970-01-01
    • 2020-08-23
    • 2015-01-24
    • 2021-03-21
    • 2016-04-02
    相关资源
    最近更新 更多