wolverine
wolverine

Reputation: 3027

How to import a DB into my iphone program?

I have a database db.sqlite3, i have copy-pasted it into the documents folder and use the code to access it inside the program.

[[[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES)
   objectAtIndex:0] stringByAppendingPathComponent:kDbName] UTF8String].

And I am able to use it while my app works in simulator.

But when i tests in device, it doesn't work. I know that we should import it into Resources and then use it. I have added it into resources, but how can i access it from inside the program?

Upvotes: 0

Views: 389

Answers (3)

Kevin Fisher
Kevin Fisher

Reputation: 715

try this:

NSString *dbPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"db.sqlite3"]; 
    if (sqlite3_open([dbPath UTF8String], &database) == SQLITE_OK) {
// do something
}

Upvotes: 1

Robin Summerhill
Robin Summerhill

Reputation: 13675

Your application needs to create a read-write version of the database in the Documents folder by copying it from Resources. See any sqlite-iphone turorial for how to do this e.g. this one

Looking at your recent questions it seems to me that you would benefit from working through a tutorial to get you on the right track.

Upvotes: 1

Vladimir
Vladimir

Reputation: 170849

Upon first launch (or in case database file is not in documents folder) copy it from resources:

NSFileManager *fileManager = [[NSFileManager defaultManager] autorelease];

if ([fileManager fileExistsAtPath: databasePath]) {
    return;
}

NSString *databasePathFromApp = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:databaseName];
[fileManager copyItemAtPath:databasePathFromApp toPath:databasePath error:nil];

Upvotes: 1

Related Questions