【问题标题】:How can we download sqlite database from url and add it into our application as sqlite database?我们如何从 url 下载 sqlite 数据库并将其作为 sqlite 数据库添加到我们的应用程序中?
【发布时间】:2012-03-28 16:54:14
【问题描述】:

我在我的应用程序中使用了 sqlite 数据库。我想将此数据库与我的 mysql 服务器同步。但我认为在我的应用程序中用新数据库替换现有数据库很容易。所以,它也将解决数据导入导出问题。但我不知道如何从我的 url 下载 .sqlite 文件并将其添加到我的应用程序包中。

以简单的方式。我想在运行时在 Xcode Resource 文件夹中添加文件。我不知道该怎么做。 如果有人有想法,请帮助我。

提前致谢。

【问题讨论】:

  • 为什么要下载 .sqlite 文件?你不会查询 MySQL 服务器然后创建本地模式并填充表吗?
  • @trojanfoe:谢谢,我不知道该怎么做。请提供更多指南以从 MYSQL 服务器更新我的本地 iPhone sqlite 数据库。

标签: iphone xcode file dynamic bundle


【解决方案1】:

要将下载的数据库作为 sqlite 数据库添加到您的应用程序,请尝试以下代码

NSString *dbfilepath = [FileUtils documentsDirectoryPathForResource:[NSString stringWithFormat:@"%@.db", @"downloadedDatabase"]];
NSData *dbData = [NSData dataWithContentsOfFile:dbfilepath];

NSString *filePath = [[FileUtils documentsDirectoryPath] stringByAppendingPathComponent:@"Database.sqlite"];

[dbData writeToFile:filePath atomically:YES];

现在您的应用程序数据库已准备好导入记录。

【讨论】:

  • 我的 web 服务器中有一个 mysql 数据库。如何在我的应用程序中将该数据库下载为 sqlite 数据库?
  • @natasha:抱歉回复晚了,要从网络服务器下载sqlite,可以参考Devang之前的回答。
【解决方案2】:

试试下面的代码:

NSData *dbFile = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:@"http://www.someurl.com/DatabaseName.sqlite"]];

NSString *resourceDocPath = [[NSString alloc] initWithString:[[[[NSBundle mainBundle]  resourcePath] stringByDeletingLastPathComponent] stringByAppendingPathComponent:@"Documents"]];

NSString *filePath = [resourceDocPath stringByAppendingPathComponent:@"Database.sqlite"];

[dbFile writeToFile:filePath atomically:YES];

现在你可以使用这个数据库文件了。

【讨论】:

  • 谢谢。它的工作。我们怎样才能看到这个“Database.sqlite”文件?是否可以将此文件添加到我的 Xcode 组文件夹中?
  • @Nit : 下载到 App 的“文档”目录。您可以通过启用“iTunes 文件共享”来验证这一点。
  • 下载到documents文件夹后,可以直接从documents文件夹访问。为什么要将它添加到“捆绑”中。即使数据库在您的包中,将数据库复制到文档文件夹然后使用它总是好的。
  • 没错,但用于验证,我也可以使用if (![fileManager fileExistsAtPath: path]) 进行验证,但我希望看到它就像我们在 Xcode 项目中看到的 .h 文件一样。
  • @Nit :正如我告诉你的那样。通过启用“iTunes 文件共享”,您将能够复制数据库,这将帮助您验证数据库。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-16
  • 1970-01-01
  • 1970-01-01
  • 2017-05-11
  • 1970-01-01
  • 2021-10-25
相关资源
最近更新 更多