1

I am new with SQLITE database and I am using FMDB. In my app I want to insert some data into the database. I used the following codes to insert data.

-(void)insertBookmark
{

    NSString *bundlePath = [[NSBundle mainBundle] bundlePath];
    NSString *dbFilePath = [bundlePath stringByAppendingPathComponent:@"ISGData.sqlite"];
    FMDatabase *database = [FMDatabase databaseWithPath:dbFilePath];
    [database open];
    [database executeUpdate:@"INSERT INTO bookmark (pageno) VALUES (?);",page, nil];
    NSLog(@"%@",[database lastErrorMessage]);
    [database close];

}

Here "bookmark" is the name of the table in my database having an entity named "pageno" of type integer. While I am passing an int value in the query app crashes showing a bad access. If i am passing a string value, in my log i am getting "not an error", but the values are not getting inserted in to the database. Is there any mistake in my code ?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Vishnu Kumar. S
  • 1,797
  • 1
  • 15
  • 35

2 Answers2

4

You are trying to modify the database inside the application bundle. The bundle itself is read-only. To do this you must first copy the database file to the documents directory and then open & modify it.

In short, replace the first three lines in your function with:

FMDatabase *database = [self openDatabase];

With openDatabase defined like in this answer: how do we open an already existing database fmdb and where to include it?

Community
  • 1
  • 1
Hampus Nilsson
  • 6,692
  • 1
  • 25
  • 29
0

Hampus is right. You need to copy it in documents directory to perform write operation:

BOOL success;
NSError *error;

NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingString:@"ISGData.sqlite"];

success = [fileManager fileExistsAtPath:filePath];
if (success) return;

NSString *path = [[[NSBundle mainBundle] resourcePath] stringByAppendingFormat:@"ISGData.sqlite"];
success = [fileManager copyItemAtPath:path toPath:filePath error:&error];

if (!success) {
    NSAssert1(0, @"Failed to copy DB. Error %@", [error localizedDescription]);
}
utsabiem
  • 920
  • 4
  • 10
  • 21