bey*_*dbo 0 sqlite exc-bad-access insert fmdb
我正在使用FMDatabase来操作sqlite3数据库.这是我的代码:
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
}
Run Code Online (Sandbox Code Playgroud)
当我运行这条线时:
BOOL result = [fmdb executeUpdate:@"INSERT INTO test1(id, name, create_time) values(?,?,?)", i+1, @"test", @"12-09-10 12:10"];
Run Code Online (Sandbox Code Playgroud)
我收到一个EXC_BAD_ACCESS错误.为什么?
问题已经解决了!
*1.*提供给-executeUpdate:方法的所有参数(或任何接受a va_list作为参数的变体)必须是对象.以下将不起作用(并将导致崩溃):
[db executeUpdate:@"INSERT INTO mytable VALUES (?)", 66];
插入数字的正确方法是框它的NSNumber对象:
[db executeUpdate:@"INSERT INTO mytable VALUES (?)", [NSNumber numberWithInt:66]];
*2*另外,你可以使用-execute*WithFormat:变种使用NSString样式替代:
[db executeUpdateWithFormat:@"INSERT INTO mytable VALUES (%d)", 66];
在内部,-execute*WithFormat:方法正确拳击事情you.The下列百分修饰符被认可:%@,%c,%s,%d,%D,%i,%u,%U,%hi,%hu,%qi,%qu,%f,%ld,%lu,%lld,和%llu.
使用除这些之外的修饰符将产生不可预测的结果.如果由于某种原因,您需要%在SQL语句中出现该字符,您应该使用%%.