Search code examples
iossqlitefmdb

Cannot insert in SQLITE database with FMDB wrapper


I'm new to IOS development so I am following this

tutorial

As mentioned in this tutorial I made my database using the SQLITE command line, created my tables and next imported the database in my XCode 4.6 Project by adding it to Supporting Files folder.

I just want to populate the table with data so I have a function that first finds my database and copies it to the Documents folder (if not there, already):

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:@"Customers.db"];
FMDatabase* db = [FMDatabase databaseWithPath:writableDBPath];

This works fine as the writebleDBPath points to the actual path where Customers.db lies (in the project's Documents folder)

Now I open the database and try to add a new record:

[db open];
BOOL success =  [db executeUpdate:@"INSERT INTO customers (firstname,lastname) VALUES (?,?);",[patient.firstName UTF8String],[patient.secondName UTF8String], nil];

[db close];

but success value is always 'NO'.

I include the code used to create the sqlite database:

CREATE TABLE customers(id integer primary key, firstname varchar(30), lastname varchar(30))

What am I missing?


Solution

  • You left out a step in the tutorial:

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

    Which copies the database file from the bundle. This assumes you created the database and it's schema and included it in the package with the app.