【问题标题】:FMDB sqlite insert failedFMDB sqlite 插入失败
【发布时间】:2012-05-23 01:00:42
【问题描述】:

来自非 SQL 背景,我创建了一个名为 test 的简单表,其中包含 3 个字段:

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

当我向表中插入一条记录时,我得到一个 exc_bad_access 错误:

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

如果我将列 'userid' 类型从整数更改为文本,这会很好。我在控制台上使用 sqlite 命令测试表,它也运行良好。 你们有什么感想?谢谢...

我尝试了另一种方法来处理这个问题:

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

然后就可以了。说不出原因……可能fmdb只支持对象插入。

【问题讨论】:

  • 只是我们的带有错误代码的 NSLog 帮助我解决了我的问题...+1

标签: insert fmdb


【解决方案1】:

我相信 FMDB 需要对象来替换 ?和 int 不是对象。把1改成[NSNumber numberWithInt:1]

另外,你在哪里打开你的数据库,你有这样的东西吗?

db = [FMDatabase databaseWithPath:writableDBPath];

    if ([db open]) {

在之后立即添加[db setTraceExecution:TRUE];,它会为您记录您的 SQL 文本。

可以先创建您的 SQL NSString,然后插入您的 int,然后让 FMDB 运行您已经填充的字符串。

【讨论】:

  • 是的,达伦,你是对的。我仔细阅读了 fmdb 文档,发现:“提供给 -executeUpdate: 方法(或任何接受 va_list 作为参数的变体)的所有参数都必须是对象。以下将不起作用(并会导致崩溃) )" 我尝试在我的代码中使用 executeUpdateWithFormat,它运行良好。我根据您的建议添加了 traceExecution 。现在我可以从 fmdb 获得更多信息。谢谢!
【解决方案2】:

executeUpdate:仅支持作为占位符值传递的对象。 您可以使用 executeQueryWithFormat: 如果您希望使用 printf 样式参数(您可以使用 %d 来表示您的号码)。不过,我个人会坚持使用对象,因为 executeQueryWithFormat: 无论如何都会最终将值转换为对象。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多