2

Unlike most sqlite apps where developers don't want to overwrite data in a sqlite database, I'm trying to enable an app to overwrite all data with future updates. The sqlite database will have the exact same name and have the same tables, I just want to be able to update the data contained in the database without making users delete the app and reinstall it. Is there an easy method to do this?

Thanks in advance!

Benjamin
  • 103
  • 2
  • 10
  • I don't know how it works out in native code, but could you not just `truncate` the tables and `insert` your records? – Kevin Peno Mar 10 '11 at 23:08

1 Answers1

7

A SQLite database file is just a normal file, so no special steps are needed. Get the path or URL to the file, and use NSFileManager's -removeItemAtPath:error: or -removeItemAtURL:error:. Then create the new database the same way you created the old one.

Tom Harrington
  • 69,312
  • 10
  • 146
  • 170
  • 1
    Thanks Tom. So for an existing database with pre-loaded info, I would merely need to insert -removeItemAtPath:error:, and each update will remove the old database and replace it with the new version? – Benjamin Mar 11 '11 at 00:55
  • That will just remove the old one. Replacing it with a new one is up to you, but you did that before so you can do it again. It'll happen every time you call the method, so you'll need to be careful about only calling it when you actually want to remove the old copy. This assumes that the database is somewhere like the documents folder, not in the app bundle. If it's in the app bundle, it's automatically overwritten on every update, but then it's also not modifiable by the user. – Tom Harrington Mar 11 '11 at 01:55
  • Sorry, this is probably a stupid question, but how do I put the database in the app bundle? I have not thought about this simple solution. Users are not going to be modifying or saving data so this would be the best solution I think. – Benjamin Mar 11 '11 at 03:26
  • I've always had sqlite databases in the documents folder so I actually don't know how to have them in the app bundle :S – Benjamin Mar 11 '11 at 04:23
  • Right now I have: *******NSString *storePath = [[self applicationDocumentsDirectory] stringByAppendingPathComponent:@"Recipes.sqlite"];********** I've tried:************NSString *defaultStorePath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"Recipes.sqlite"];**********But this returns an error :( – Benjamin Mar 11 '11 at 05:15
  • GOT IT!!! WOO HOO! Totally worth the hours of trial and error! I was hiding the NSFileManager and NSURL. That is why it was giving the error. I unhid these and it worked. :) Knew I was close. Gotta love trial and error. Thanks for turning me in the right direction Tom. – Benjamin Mar 11 '11 at 05:27