【问题标题】:Primary Key Insertion - SQLite with Objective-C主键插入 - 带有 Objective-C 的 SQLite
【发布时间】:2014-09-04 23:25:08
【问题描述】:

我正在尝试使用 Objective-C 将用户信息写入 SQLite 数据库。我在 SQLite 网站常见问题解答 (http://www.sqlite.org/faq.html) 上阅读,输入 NULL 代替主键,我已经这样做了。但是,当我执行NSLog(@"%d",sqlite3_step(sqlStatement) 时,我得到错误代码 20(数据类型不匹配)。下面是相关代码。

在任何人问之前,我已经在以前的代码中适当地打开了数据库,所以这不是问题。 writableDBPath 为数据库路径,验证有效。

sqlite3_stmt *sqlStatement;
    NSString *momentInsertSQL = [NSString stringWithFormat:@"INSERT INTO MomentTbl (momentID, albumID, title, timestamp, author, latitude, longitude, canvas) VALUES (\"%@\", \"%d\", \"%@\", \"%@\", \"%@\", \"%@\", \"%@\", \"%@\")",NULL, alb.ID, alb.title, m.timestamp, @"user", m.latitude, m.longitude, m.moment];
    const char *query_stmt = [momentInsertSQL UTF8String];
    const char *dbPath = [writableDBPath UTF8String];
    if(sqlite3_open(dbPath, &db) == SQLITE_OK) {
        if(sqlite3_prepare(db, query_stmt, -1, &sqlStatement, NULL) == SQLITE_OK)
        {
            sqlite3_prepare_v2(db, query_stmt, -1, &sqlStatement, NULL);

            NSLog(@"%d", sqlite3_step(sqlStatement));
            if(sqlite3_step(sqlStatement) == SQLITE_DONE)
                NSLog(@"OK");
            else
                NSLog(@"Problem");

            sqlite3_finalize(sqlStatement);
            sqlite3_close(db);
        }
    }

当我用数字替换NULL时,返回的代码是101,应该是SQLITE_DONE,但是NSLog仍然显示“Problem”。感谢任何帮助,作为 SQLite 的新手,我真的需要它。

【问题讨论】:

  • Emm...你不应该给你的主键赋值!
  • 所以我应该将 momentID 及其对应的值 NULL 完全从我的插入语句中移除?
  • 仅供参考 - 使用 stringWithFormat 构建查询是一种糟糕的做法。请以正确的方式进行(使用各种sqlite3_bind_xxx 函数)。

标签: ios sql objective-c database sqlite


【解决方案1】:

SQL NULL 不同于 C NULL

将值中的第一个 \"%@\" 替换为文字 NULL 并从格式参数中删除 NULL,例如:

NSString *momentInsertSQL = [NSString stringWithFormat:@"INSERT INTO MomentTbl (momentID, albumID, title, timestamp, author, latitude, longitude, canvas) VALUES (NULL, \"%d\", \"%@\", \"%@\", \"%@\", \"%@\", \"%@\", \"%@\")", alb.ID, alb.title, m.timestamp, @"t-panda", m.latitude, m.longitude, m.moment];

或者,您可以完全省略主键 momentID。 sqlite 在您未指定值的列中插入NULL

【讨论】:

  • 将我的代码更改为您所说的后,NSLog返回的代码是101。SQLite的网站说这相当于SQLITE_DONE,但if(sqlite3_step(sqlStatement) == SQLITE_DONE)仍然评估为false。
  • 没关系 - 删除 NSLog 语句解决了这个问题。谢谢!
【解决方案2】:

我认为这是因为您有两个 sqlite3_step 调用,而两者之间没有 sqlite3_reset

NSLog 中的那个返回 101 (SQLITE_DONE),但 if 语句中的那个可能返回 SQLITE_MISUSE (http://www.sqlite.org/c3ref/step.html)。

【讨论】:

    猜你喜欢
    • 2013-02-09
    • 2014-03-10
    • 1970-01-01
    • 2013-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-15
    • 1970-01-01
    相关资源
    最近更新 更多