简体   繁体   English

iPhone在运行时创建SQLite数据库?

[英]iPhone create SQLite database at runtime?

Most sqlite examples I've found talk about creating a db file from the commandline first and then adding that to your app. 我发现的大多数sqlite示例都是先从命令行创建一个db文件,然后再添加到你的应用程序中。 For my project, I'd like to be able to create my database within the app when it starts up for the first time and then save it to a db file in the user's sandbox. 对于我的项目,我希望能够在第一次启动时在应用程序中创建我的数据库,然后将其保存到用户沙箱中的db文件中。 Is there a way to do that? 有没有办法做到这一点?

You can check for the file (as usual) when the application starts up. 您可以在应用程序启动时检查文件(照常)。 If the file does not exist, instead of copying the pre-created file, simply: 如果文件不存在,而不是复制预先创建的文件,只需:

  1. Open the file as usual using sqlite3_open() 像往常一样使用sqlite3_open()打开文件
  2. Run your creation commands (ie, create your tables, views, etc.) 运行您的创建命令(即,创建表,视图等)

That's really all there is to it. 这就是它的全部内容。

I think I'm going to echo the expanding cry, that if you are looking at doing anything with a database you should look at CoreData. 我想我会回应不断扩大的呐喊,如果你正在寻找使用数据库做任何事情,你应该看看CoreData。 It uses SQLLite underneath and is simpler to set up, and much simpler to migrate later when you find you need a few new things in the DB! 它使用下面的SQLLite并且设置起来简单,并且当您发现数据库中需要一些新东西时,以后更容易迁移!

Core Data provides an easy way to manage this - it will look for a database file upon start-up if none exists it will create one for you. 核心数据提供了一种简单的方法来管理它 - 它会在启动时查找数据库文件,如果不存在,它将为您创建一个。 It will also create the model for you automatically based on a diagram that you can create in xCode. 它还将根据您可以在xCode中创建的图表自动为您创建模型。

When you come to upgrading people with older databases in the future it will also simplify data migration. 当您将来使用旧数据库升级人员时,它还将简化数据迁移。

You access the data with generated Data objects too. 您也可以使用生成的Data对象访问数据。 Core Data will also use lazy loading for the objects it creates, which is much better than having to manually 核心数据也将对其创建的对象使用延迟加载,这比必须手动更好

For more information see the Locations demo project and read up on Core Data in the documentation. 有关更多信息,请参阅位置演示项目并阅读文档中的Core Data。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM