数据被插入SQLITE3上的错误列

时间:2018-04-23 06:14:43

标签: swift sqlite

我试图将用户输入的数据插入到我设置的SQLite数据库中。这是我目前编写的代码:

var stmt: OpaquePointer?
let queryString = "INSERT INTO entries (id, name, email, avatar) VALUES (NULL,?,?,?)"

if(sqlite3_prepare_v2(db, queryString, -1, &stmt, nil) == SQLITE_OK){
        sqlite3_bind_text(stmt, 1, strName, -1, nil)
        sqlite3_bind_text(stmt, 2, strEmail, -1, nil)
        sqlite3_bind_text(stmt, 3, "batman", -1, nil)
    }

else{
        let errMsg = String(cString: sqlite3_errmsg(db)!)
        print("error preparing insert: \(errMsg)")
        return
}

strName和strEmail正在从文本字段中提取。当我在另一个视图中查询此数据时,出于某种原因" batman"已插入第二列而不是用户输入。这是选择查询:

let queryString = "SELECT * FROM entries"
var stmt: OpaquePointer?

if sqlite3_prepare_v2(db, queryString, -1, &stmt, nil) != SQLITE_OK{
        let errmsg = String(cString: sqlite3_errmsg(db)!)
        print("error preparing select: \(errmsg)")
        return
}

while(sqlite3_step(stmt) == SQLITE_ROW){
        let id = sqlite3_column_int(stmt, 0)
        let name = String(cString: sqlite3_column_text(stmt, 1))
        let email = String(cString: sqlite3_column_text(stmt, 2))

        userList.append(User(id: Int(id), name: String(describing: name), email: String(describing: email)))
        print (id);
        print (name);
        print (email);
}

我期望从输出中看到的是:

  1. 1
  2. 用户名
  3. 用户电子邮件
  4. 我反而看到了:

    1. 1
    2. 蝙蝠侠
    3. 用户电子邮件
    4. 我的插入声明是否有问题?

1 个答案:

答案 0 :(得分:4)

找到答案:

sqlite3_bind_text存在导致不正确数据插入错误行的问题。

更改了以下的绑定语句:

sqlite3_bind_text(stmt, 1, strName, -1, nil)
sqlite3_bind_text(stmt, 2, strEmail, -1, nil)
sqlite3_bind_text(stmt, 3, "batman", -1, nil)

为:

sqlite3_bind_text(stmt, 1, strName, -1, SQLITE_TRANSIENT)
sqlite3_bind_text(stmt, 2, strEmail, -1, SQLITE_TRANSIENT)
sqlite3_bind_text(stmt, 3, "batman", -1, SQLITE_TRANSIENT)

SQLITE_TRANSIENT定义为:

let SQLITE_TRANSIENT = unsafeBitCast(OpaquePointer(bitPattern: -1), to: sqlite3_destructor_type.self)

查询时数据现在可以正常返回。