Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. 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. Is there a way to do that?

like image 212
Cruinh Avatar asked Jun 19 '09 19:06

Cruinh


3 Answers

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()
  2. Run your creation commands (i.e., create your tables, views, etc.)

That's really all there is to it.

like image 92
Jason Coco Avatar answered Sep 18 '22 19:09

Jason Coco


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. 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!

like image 28
Kendall Helmstetter Gelner Avatar answered Sep 22 '22 19:09

Kendall Helmstetter Gelner


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.

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. 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.

like image 33
Grouchal Avatar answered Sep 18 '22 19:09

Grouchal