【问题标题】:How to import a DB into my iphone program?如何将数据库导入我的 iphone 程序?
【发布时间】:2010-01-06 13:13:53
【问题描述】:

我有一个数据库 db.sqlite3,我已将其复制粘贴到文档文件夹中,并使用代码在程序中访问它。

[[[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES)
   objectAtIndex:0] stringByAppendingPathComponent:kDbName] UTF8String].

当我的应用在模拟器中运行时,我可以使用它。

但是当我在设备中测试时,它不起作用。我知道我们应该将它导入到 Resources 中然后使用它。我已将其添加到资源中,但是如何从程序内部访问它?

【问题讨论】:

    标签: iphone ios-simulator


    【解决方案1】:

    试试这个:

    NSString *dbPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"db.sqlite3"]; 
        if (sqlite3_open([dbPath UTF8String], &database) == SQLITE_OK) {
    // do something
    }
    

    【讨论】:

    • 是的,请记住,在这种情况下,您将无法向数据库写入任何内容。
    • 非常感谢。我知道它很简单,但不知道为什么,不知道为什么。
    【解决方案2】:

    第一次启动时(或者如果数据库文件不在文档文件夹中)从资源中复制它:

    NSFileManager *fileManager = [[NSFileManager defaultManager] autorelease];
    
    if ([fileManager fileExistsAtPath: databasePath]) {
        return;
    }
    
    NSString *databasePathFromApp = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:databaseName];
    [fileManager copyItemAtPath:databasePathFromApp toPath:databasePath error:nil];
    

    【讨论】:

    • 这也对我有用。但是由于我没有任何东西要写入 DB,所以我使用了之前的那个。无论如何,非常感谢。
    【解决方案3】:

    您的应用程序需要通过从资源复制数据库在 Documents 文件夹中创建数据库的读写版本。请参阅任何 sqlite-iphone 教程以了解如何执行此操作,例如this one

    查看您最近提出的问题,在我看来,通过教程让您走上正轨,您会受益匪浅。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-05
      • 1970-01-01
      相关资源
      最近更新 更多