sr1972
sr1972

Reputation: 61

sqlite connection with Objective C

I have a simple piece of code where I connect my sqliteDb. My sqlite3_prepare_v2 though repeatedly fails. I narrowed it down to the following piece of code:

NSString *sqLiteDb = [[NSBundle mainBundle] pathForResource:@"xyz" ofType:@"sqlite3"];

sqLiteDb returns null. I don't know why - tried everything I could and followed many threads. Really struggling here - please help.

Upvotes: 3

Views: 694

Answers (2)

iAppDeveloper
iAppDeveloper

Reputation: 1088

Try this

in.h file

 NSString *databasePath;


in .m file


NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,               NSUserDomainMask, YES);
  NSString *documentsDir = [documentPaths objectAtIndex:0];
  databasePath = [documentsDir stringByAppendingPathComponent:@"dbname.sqlite"];    
  [self checkAndCreateDatabase];

-(void) checkAndCreateDatabase
    {
     // Check if the SQL database has already been saved to the users phone, if not then copy it over
     BOOL success;

     // Create a FileManager object, we will use this to check the status
     // of the database and to copy it over if required
     NSFileManager *fileManager = [NSFileManager defaultManager];

     // Check if the database has already been created in the users filesystem
     success = [fileManager fileExistsAtPath:databasePath];

     // If the database already exists then return without doing anything
     if(success) return;

     // If not then proceed to copy the database from the application to the users filesystem

     // Get the path to the database in the application package
     NSString *databasePathFromApp = [[[NSBundle mainBundle] resourcePath]  stringByAppendingPathComponent:databaseName];

     // Copy the database from the package to the users filesystem
     [fileManager copyItemAtPath:databasePathFromApp toPath:databasePath error:nil];

   }

Upvotes: 1

dreamlax
dreamlax

Reputation: 95315

Are you sure your xyz.sqlite3 file is included in the correct Target Membership? If it is not included, then it will not be copied to your bundle when building.

Screenshot

Upvotes: 1

Related Questions