Search code examples
iphoneiossqlitexcode4.2fmdb

how do we open an already existing database fmdb and where to include it?


I am using fmdb but i am not knowing where to add the db file. I found this old answer that i think it doesn't fit for xcode 4.2 (since we dont have 'Resources' folder anymore).

I created a database in 'Lita', added the extension .sqlite and added the db file as follows :

dbsqlite

then tried to use the following

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docsPath = [paths objectAtIndex:0];
NSString *path = [docsPath stringByAppendingPathComponent:@"db.sqlite"];
FMDatabase *database = [FMDatabase databaseWithPath:path];
[database open];
FMResultSet *results = [database executeQuery:@"select * from tbl"];
printf("hi");
while([results next]) {
    printf("hi2");
NSString *name = [results stringForColumn:@"clm1"];
NSString *text  = [results stringForColumn:@"clm2"];        
NSLog(@"test: %@ - %@",name, text);
}
printf("done");

i am getting the 'hi' 'done' but never 'hi2'...

anyone can help?


Solution

  • You want to add the (compiled) database to the project as a resource, and then copy it into the documents folder of the app on first start-up.

    Here is an example method that does the work, call it from the applicationDidFinishLaunching and use the resultant FMDatabase * for all you queries.

    - (FMDatabase *)openDatabase
    {
        NSFileManager *fm = [NSFileManager defaultManager];
        NSString *documents_dir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
        NSString *db_path = [documents_dir stringByAppendingPathComponent:[NSString stringWithFormat:@"database.s3db"]];
        NSString *template_path = [[NSBundle mainBundle] pathForResource:@"template_db" ofType:@"s3db"];
    
        if (![fm fileExistsAtPath:db_path])
            [fm copyItemAtPath:template_path toPath:db_path error:nil];
        FMDatabase *db = [FMDatabase databaseWithPath:db_path];
        if (![db open])
            NSLog(@"Failed to open database!");
        return db;
    }