FMDB insert query executed but not inserting data in database

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 ?

Answers


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?


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]);
}

Need Your Help

Find common columns between two users or null/zero if there is none

php mysql sql

How can I find common columns between 2 users but returning a zero result if there is none, that means returning a result even if there is no common columns.

Stream containing Html encoding and special characters issue

.net encoding stream

My program reads a web page content with by issuing a HttpWebRequest and reading a stream from HttpWebResponse.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.