【问题标题】:Import an existing SQLite database into an iOS Phonegap app将现有 SQLite 数据库导入 iOS Phonegap 应用程序
【发布时间】:2012-11-17 17:32:48
【问题描述】:

我有一个名为 data_items.sqlite 的现有 SQLite 数据库。这个数据库包括大约 10 个表和一些初始数据,我想将它们导入 XCode 以通过这种方式使用 Phonegap 插件打开数据库:

function onDeviceReady() {
    var db = window.sqlitePlugin.openDatabase("data_items.sqlite", "1.0", "PhoneGap Demo", 200000);
    ...
}

如何导入数据文件?我必须在哪里复制文件?

【问题讨论】:

    标签: sqlite cordova


    【解决方案1】:

    似乎无法从PhoneGap访问assets文件夹,所以你必须编写一个原生插件来复制数据库文件:
    Prepopulate SQLite DataBase in PhoneGap Application

    【讨论】:

      【解决方案2】:

      首先创建数据库,因为您使用名称 data_items.sqlite 并删除 .sqlite 扩展名。然后将这个db拖到xCode中的Resources目录下,然后下一步。

      将出现选择添加文件框的选项 选中复选框“将项目复制到目标组的文件夹(如果需要)”并完成。

      您将看到数据库文件作为资源目录的子列表

      抱歉,我没有足够的声望在这里发布图片

      现在点击链接将此数据库文件复制到位置

      How to copy sqlite database when application is launched in iOS?

      我在 AppDelegate.m 的最后一行 @end 之前使用了以下代码

          - (void) copyDatabaseIfNeeded{
              NSFileManager *fileManager = [NSFileManager defaultManager];
              NSError *error;
              _dbPath = [self getDBPath];
      
              BOOL success = [fileManager fileExistsAtPath:_dbPath];
      
          if(!success){
              NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"data_items"];
              success = [fileManager copyItemAtPath:defaultDBPath toPath:_dbPath error:&error];
              if (!success)
                  NSAssert1(0, @"Failed to create writable database file with message '%@'.", [error localizedDescription]);
          }}
      /********* Database Path *********/
      - (NSString *) getDBPath
      {
          NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
          NSString *documentsDir = [paths objectAtIndex:0];
      
          return [documentsDir stringByAppendingPathComponent:@"data_items"];
      }
      

      并复制该行

      [self copyDatabaseIfNeeded];
      

      代码之后

      - (BOOL)application:(UIApplication*)application didFinishLaunchingWithOptions:(NSDictionary*)launchOptions
      {
          CGRect screenBounds = [[UIScreen mainScreen] bounds];
      

      就是这样。使用你的代码

      function onDeviceReady() {
          var db = window.sqlitePlugin.openDatabase("data_items", "1.0", "data_items", 200000);
          ...
      }
      

      您也可以直接从复制的位置编辑数据库。使用以下链接

      Where does the iPhone Simulator store its data?

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-01-28
        • 1970-01-01
        • 2013-10-31
        • 1970-01-01
        相关资源
        最近更新 更多