Search code examples
insertfmdb

FMDB sqlite insert failed


Coming from a non-SQL background, i create a simple table, named test, with 3 fields:

    NSString *testtable = @"create table if not exists test(testid integer primary key, userid integer, contentid text)";
if (![db executeUpdate:testtable]) {
    NSLog(@"create test, %d:%@", [db lastErrorCode], [db lastErrorMessage]);
    return NO;
}

when i insert a record to the table ,i got an exc_bad_access error:

    if (![db executeUpdate:@"insert into test values(?,?,?)", NULL, 1, @"HELLO"]) {
    NSLog(@"insert test, %d:%@", [db lastErrorCode], [db lastErrorMessage]);
    return NO;
}

If i change column 'userid' type from integer to text ,this will work well. And i test the table using sqlite command on the console, it works well too. What do you guys think? Thanks...

i try another way to handle this problem:

    if (![db executeUpdate:@"insert into test values(?,?,?)", NULL, [NSNumber numberWithInt:1], @"HELLO"]) {
    NSLog(@"testint, %d:%@", [db lastErrorCode], [db lastErrorMessage]);
    return NO;
}

then it works. I can not tell the reason... Maybe fmdb only supports object insert.


Solution

  • I believe FMDB needs objects to replace the ? and int's are not objects. Change the 1 to [NSNumber numberWithInt:1]

    Also, where you open your database you have something like this?

    db = [FMDatabase databaseWithPath:writableDBPath];
    
        if ([db open]) {
    

    Add [db setTraceExecution:TRUE]; immediately after and it'll nslog your SQL text for you.

    It is possible to create your SQL NSString first, and insert your int, then get FMDB to just run your already populated string.