FMDB数据库不在设备上工作,但它在Simulator中工作

时间:2014-08-12 13:12:45

标签: ios database sqlite fmdb

我有我创建的这个数据库,我想用FMDB加载它,但在模拟器上我可以查询选择数据,但不能在ipad上。

我使用此代码进行检查。

- (void)createDatabase{
    //set reference to database here

    BOOL success;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSError *error;
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    // Database filename can have extension db/sqlite.
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *appDBPath = [documentsDirectory stringByAppendingPathComponent:@"product.db"];

    success = [fileManager fileExistsAtPath:appDBPath];
    if (success) {
        [self getAllData];
        return;
    }
    // The writable database does not exist, so copy the default to the appropriate location.
    NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"product.db"];
    success = [fileManager copyItemAtPath:defaultDBPath toPath:appDBPath error:&error];
    NSAssert(success, @"Failed to create writable database file with message '%@'.", [error localizedDescription]);
    [self getAllData];
}

//method used to create database and check if it exists

- (void)getAllData {
    // Getting the database path.
    NSArray  *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *docsPath = [paths objectAtIndex:0];
    NSString *dbPath = [docsPath stringByAppendingPathComponent:@"product.db"];

    database = [FMDatabase databaseWithPath:dbPath];
    [database open];
    NSString *sqlSelectQuery = @"SELECT * FROM Categories";

    // Query result
    FMResultSet *resultsWithNameLocation = [database executeQuery:sqlSelectQuery];
    while([resultsWithNameLocation next]) {
        NSString *strID = [NSString stringWithFormat:@"%d",[resultsWithNameLocation intForColumn:@"id"]];
        NSString *strName = [NSString stringWithFormat:@"%@",[resultsWithNameLocation stringForColumn:@"cat"]];
        NSString *strLoc = [NSString stringWithFormat:@"%@",[resultsWithNameLocation stringForColumn:@"Location"]];

        // loading your data into the array, dictionaries.
        NSLog(@"ID = %@, Name = %@, Location = %@",strID, strName, strLoc);
    }
    [database close];
}

我将product.db放在支持文件中,然后将其复制到目标的Copy Bundle Resources中。有谁做错了什么?我在这里走到了尽头。

提前致谢

问题出现在选择阶段,当我选择它时它会返回:

  

"数据库错误:1"没有这样的表"

1 个答案:

答案 0 :(得分:2)

如果您在优化文件打开/复制逻辑之前在设备上运行了应用程序,则可能在文档文件夹中意外创建了一个空白数据库(因为如果您打开数据库但未找到它,它创建一个空白数据库)。尝试删除应用程序(这将删除任何可能遗留下来的空白数据库)并重新安装应用程序,看看是否修复了它。

顺便说一下,将来,您可以使用openWithFlags(而非openSQLITE_OPEN_READWRITE(但不是SQLITE_OPEN_CREATE)来避免此问题将确保应用程序永远不会创建一个空白数据库,如果它找不到。

您可以在sqlite3_open {FMDB open使用的)和sqlite_open_v2(FMDB openWithFlags使用的)上查看SQLite documentation来讨论这些标记