FMDB没有插入DB

时间:2011-08-13 11:16:23

标签: iphone fmdb


我正在尝试使用FMDB将一些查询插入到数据库中。
当我检查插入的查询时,它说它正在插入。
后来我实际上可以从表中读取数据。
但是,如果我尝试从数据库中读取信息,它会返回null。
当我在Xcode项目中检查数据库时,似乎没有更新。
这让我很困惑。有什么建议可以解决问题吗?

1 个答案:

答案 0 :(得分: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];

还要检查我在哪里找到db。我认为按照自己的方式可以在模拟器上工作,但不能在设备上工作,因为沙盒和所有。

祝你好运!

编辑:

将其放入您的app delegate:

- (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];

请务必先将数据库放在项目树中。