iOS - FMDB数据库插入

时间:2012-04-11 10:53:14

标签: iphone ios5 sqlite fmdb

要使用sqlite将数据插入数据库,需要复制数据库以使其可写。所以我在课堂上有这个方法,我在堆栈上看到的每个建议都溢出了许多其他网站:

-(void)createEditableCopyOfDatabaseIfNeeded 
{  
    BOOL success;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSError *error;

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

    NSString *documentsDirectory = [paths objectAtIndex:0];

    NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:@"sample.db"];

    success = [fileManager fileExistsAtPath:writableDBPath];

    if (success) return;
    NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"sample.db"];
    success = [fileManager copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error];
        if (!success) {
            NSAssert1(0, @"Failed to create writable database file with message '%@'.", [error localizedDescription]);
        }

}

当然我有下一个代码来访问我的数据库:

FMDatabase *db; = [FMDatabase databaseWithPath:[[NSBundle mainBundle] pathForResource:@"sample" ofType:@"db"]];
if (![db open]) {
    NSLog(@"Error!");
}
else {
    NSLog(@"Database opened!!");
}

[self createEditableCopyOfDatabaseIfNeeded];
[db executeUpdate:@"Insert into user (name, phone, comment) values(?, ?, ?)", @"Name1", @"13548", @"This is a comment", nil];
NSLog(@"Inserted");

FMResultSet *s = [db executeQuery:@"SELECT * FROM user"];
while ([s next]) {
    NSLog(@"%@", [s stringForColumn:@"comment"]);
}

现在,我有几个问题:

  1. 插入代码在执行/运行时在模拟器中完美运行。但是,这对真正的sample.db没有影响,我得出结论,它必须在我的mac的硬盘驱动器中有一个可写副本。这是可以接受的。但是当我在iphone上运行这些代码时,它有点无法识别我的createEditableCopyOfDatabaseIfNeeded方法,并给出了此错误:Unknown error finalizing or resetting statement > (8: attempt to write a readonly database)。如何使用FMDB使这些代码正常工作?

  2. 在iPhone上运行时,复制数据库位于何处?复制后,即使没有连接到我的Mac,iPhone也会再次使用该数据库吗?

  3. 在设备上运行时无法插入内容。 请帮忙。

    非常感谢你!

2 个答案:

答案 0 :(得分:5)

如果您正在阅读本文,那么我会解释您的问题。

  1. 如果资源包中有任何文件,则它是READ-ONLY文件。因此,您的资源目录的数据库路径仅供阅读。

  2. 根据您为复制数据库而编写的代码,将在应用程序的文档目录中创建数据库。即使您从Mac上移除iPhone,此路径也不会受到影响。

答案 1 :(得分:0)

尝试将其插入数据库

[db open];

FMResultSet *results = [db executeQueryWithFormat:@"SELECT cms_desc FROM cms_media where cms_name=%@",@"name"];

NSString *str;

while([results next]) 

{

    str=[results stringForColumn:@"cms_desc"];
}

[results close];

[db close];

只需拖放项目中的.sqlite文件,然后在设备中重置应用

即可