0

How can I save my FMDatabase database to SQLite database (.db) in my project?

I have a TableView, where I display my Sqlite database (.db) with FMDatabase. I changed that database with executeUpdate, but I can't apply this changes to the original sqlite database (.db) in my project.

I poorly know English and original tutorials are difficult for me. I hope you can help me understand.

Ike
  • 9
  • 5
  • 1
    The database FMDB saves to _is_ a SQLite database, so I'm unclear what you're asking. You use FMDB to open the SQLite database that is in your Documents folder (which you either copied from bundle or you created programmatically). You never alter the database in the bundle (if you even have one there, at all). Can you clarify your question? – Rob Jan 19 '14 at 13:25
  • Got it! I solved my problem. I just wrote these strings: NSString *path = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"Base.db"]; NSString *path2 = [DOCUMENTS stringByAppendingPathComponent:@"Base.db"]; if (![[NSFileManager defaultManager] fileExistsAtPath:path2]) { NSData *xmlData = [NSData dataWithContentsOfFile:path]; [xmlData writeToFile:path2 atomically:YES]; } – Ike Jan 19 '14 at 14:34
  • 1
    Yep. I might suggest using `copyItemAtPath` rather than round-tripping it through a `NSData`, but this is essentially correct. – Rob Jan 19 '14 at 15:08

1 Answers1

0

The database FMDB saves to is, itself, a SQLite database. You use FMDB to open the SQLite database that is in your Documents folder (which you either copied from bundle or you created programmatically). You never alter the database in the bundle (if you even have one there, at all).

What you will generally do is check to see if the database exists in Documents, and if not, copy it there from the bundle:

NSString *bundlePath = [[NSBundle mainBundle] pathForResource:@"Base" ofType:@"db"];
NSString *documentsFolder = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
NSString *documentsPath = [documentsFolder stringByAppendingPathComponent:@"Base.db"];
NSFileManager *fileManager = [NSFileManager defaultManager];

if (![fileManager fileExistsAtPath:documentsPath]) {
    NSError *error;
    BOOL success = [fileManager copyItemAtPath:bundlePath toPath:documentsPath error:&error];
    NSAssert(success, @"%s: copyItemAtPath error: %@", __FUNCTION__, error);
}

// now FMDB can use the database at `documentsPath`
Donal Fellows
  • 133,037
  • 18
  • 149
  • 215
Rob
  • 415,655
  • 72
  • 787
  • 1,044