0

I'm using FMDatabase to operate on an sqlite3 database. Here's my code:

NSString *dbFilePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:[NSString stringWithFormat:@"temp_info.db"]];

FMDatabase *fmdb = [FMDatabase databaseWithPath:dbFilePath];
if (![fmdb open]) {
    NSLog(@"......");
} else {
    NSString *sql = @"CREATE TABLE IF NOT EXISTS test1(id INTEGER, name TEXT, create_time TEXT)";
    if (![fmdb executeUpdate:sql]) {
        NSLog(@"......");
    }
    for (int i = 0; i < 3; i++) {
        BOOL result = [fmdb executeUpdate:@"INSERT INTO test1(id, name, create_time) values(?,?,?)", i+1, @"test", @"12-09-10 12:10"];
        NSLog(@"%d", result);
    }
    // EXC_BAD_ACCESS
}

When I run the line:

BOOL result = [fmdb executeUpdate:@"INSERT INTO test1(id, name, create_time) values(?,?,?)", i+1, @"test", @"12-09-10 12:10"];

I get an EXC_BAD_ACCESS error. Why?

richsage
  • 26,912
  • 8
  • 58
  • 65
beyondbo
  • 91
  • 5
  • If you have solved the question you still need to accept your own answer. This will mark the question closed. – Artemix Sep 17 '12 at 19:40

1 Answers1

9

question has been solved!
*1.*All arguments provided to the -executeUpdate: method(or any of the variants that accept a va_list as a parameter) must be objects.The following will be not work (and will result in a crash):
[db executeUpdate:@"INSERT INTO mytable VALUES (?)", 66];
The proper way to insert a number is to box it in an NSNumber object:
[db executeUpdate:@"INSERT INTO mytable VALUES (?)", [NSNumber numberWithInt:66]];
*2.*Alternatively,you can use the -execute*WithFormat: variant to use NSString-style substitution:
[db executeUpdateWithFormat:@"INSERT INTO mytable VALUES (%d)", 66];
Internally,the -execute*WithFormat: methods are properly boxing things for you.The following percent modifiers are recognized:
%@,%c,%s,%d,%D,%i,%u,%U,%hi,%hu,%qi,%qu,%f,%ld,%lu,%lld,and %llu.
Using a modifier other than those will have unpredictable results.If,for some reason,you need the % character to appear in your SQL statement,you should use %%.

beyondbo
  • 91
  • 5