我正在向SQLite数据库行写入多个值,但是,它只将最后一个值写入行中的所有单元格。我怎样才能解决这个问题?代码如下:
//creating a statement
var insertStatement: OpaquePointer? = nil
//the insert query
let queryString = "INSERT INTO Users (title, firstName, lastName, email, affiliatedOrg, region, privacyRequest) VALUES (?,?,?,?,?,?,?);"
if sqlite3_prepare_v2(db, queryString, -1, &insertStatement, nil) == SQLITE_OK {
sqlite3_bind_text(insertStatement, 1, titleField, -1, nil)
sqlite3_bind_text(insertStatement, 2, firstNameField, -1, nil)
sqlite3_bind_text(insertStatement, 3, lastNameField, -1, nil)
sqlite3_bind_text(insertStatement, 4, emailField, -1, nil)
sqlite3_bind_text(insertStatement, 5, affiliatedOrgField, -1, nil)
sqlite3_bind_text(insertStatement, 6, ukRegionField, -1, nil)
sqlite3_bind_text(insertStatement, 7, privacyString, -1, nil)
if sqlite3_step(insertStatement) == SQLITE_DONE {
print("Successfully inserted row.")
} else {
print("Could not insert row.")
}
} else {
print("INSERT statement could not be prepared.")
}
sqlite3_finalize(insertStatement)
非常感谢提前。
答案 0 :(得分:2)
您应该使用SQLITE_TRANSIENT
作为sqlite3_bind_text
的最后一个参数,如https://stackoverflow.com/a/28642293/1271826中所述。正如SQLite documentation所说:
SQLITE_TRANSIENT
值意味着内容可能会在不久的将来发生变化,并且SQLite应该在返回之前制作自己的内容私有副本。
所以,你应该:
sqlite3_bind_text(insertStatement, 1, titleField, -1, SQLITE_TRANSIENT)
其中,
internal let SQLITE_STATIC = unsafeBitCast(0, to: sqlite3_destructor_type.self)
internal let SQLITE_TRANSIENT = unsafeBitCast(-1, to: sqlite3_destructor_type.self)
但是,底线SQLITE_TRANSIENT
将确保SQLite将复制数据,而不依赖于Swift内部内存管理来获取这些绑定值。