0


我正在尝试使用 FMDB 将一些查询插入数据库。
当我检查插入查询时,它说它正在插入。
后来我实际上可以从表格中读取数据。
但是发生的情况是,如果我尝试从数据库中读取信息,它会返回为空。
当我在 Xcode 项目中检查数据库时,似乎没有更新。
这让我有点困惑。任何建议可能是什么问题?

4

1 回答 1

4

你的代码是错误的。这是我用来写的:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *dbPath = [documentsDirectory stringByAppendingPathComponent:@"db.sqlite"];

FMDatabase *db = [FMDatabase databaseWithPath:dbPath];
[db open];

[db executeUpdate:@"INSERT INTO foo (bar) VALUES (?)", bar];

[db close];

并阅读:

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *dbPath = [documentsDirectory stringByAppendingPathComponent:@"db.sqlite"];

    FMDatabase *db = [FMDatabase databaseWithPath:dbPath];
    [db open];

    NSMutableArray *bar = [[[NSMutableArray alloc] init] autorelease];

    FMResultSet *s = [db executeQuery:@"select * from foo"];
    while ([s next]) {

        [bar addObject:[s stringForColumn:@"bar"]];

    }

    NSLog(@"%@", bar);

    [db close];

还要检查我找到数据库的位置。我认为按照你的方式在模拟器上工作,但由于沙盒和所有的原因,不能在设备上工作。

祝你好运!

编辑:

把它放在你的应用委托中:

- (void)createEditableCopyOfDatabaseIfNeeded {


    // First, test for existence.
    BOOL success;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSError *error;
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:@"db.sqlite"];
    success = [fileManager fileExistsAtPath:writableDBPath];
    if (success) return;
    // The writable database does not exist, so copy the default to the appropriate location.
    NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"db.sqlite"];
    success = [fileManager copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error];
    if (!success) {
        NSAssert1(0, @"Failed to create writable database file with message '%@'.", [error localizedDescription]);
    }
}

并通过以下方式运行该方法application:didFinishLaunchingWithOptions

[self performSelector:@selector(createEditableCopyOfDatabaseIfNeeded) withObject:nil];

确保首先将数据库放在项目树中。

于 2011-08-13T12:45:31.287 回答