我在 swift 中的 sqlite3 实现中遇到了一点问题,无法更新余额字段。
该表定义如下:
class User {
var id: Int
var uid: String
var balance: Double
var password: String
var address: String
init(id: Int, uid: String, balance: Double, password: String, address: String) {
self.id = id
self.uid = uid
self.balance = balance
self.password = password
self.address = address
}
}
它正在被创建,没有任何问题。
我在创建时使用以下代码编写初始记录:
func insertUser(id: Int, uid: String, balance: Double, password: String) -> Bool{
let users = getAllUsers()
// Check user email is exist in User table or not
for user in users{
if user.id == id {
return false
}
}
let insertStatementString = "INSERT INTO User (id, uid, balance, password, address) VALUES (?, ?, ?, ?, ?);"
var insertStatement: OpaquePointer? = nil
if sqlite3_prepare_v2(db, insertStatementString, -1, &insertStatement, nil) == SQLITE_OK {
sqlite3_bind_int(insertStatement, 1, Int32(id))
sqlite3_bind_text(insertStatement, 2, (uid as NSString).utf8String, -1, nil)
sqlite3_bind_double(insertStatement, 3, Double(balance))
sqlite3_bind_text(insertStatement, 4, (password as NSString).utf8String, -1, nil)
sqlite3_bind_text(insertStatement, 5, "", -1, nil) // assign empty value to address
if sqlite3_step(insertStatement) == SQLITE_DONE {
print("User is created successfully.")
sqlite3_finalize(insertStatement)
return true
} else {
print("Could not add.")
return false
}
} else {
print("INSERT statement is failed.")
return false
}
}
到目前为止,一切都按预期进行。所有字段都已适当设置。
我尝试使用以下代码更新余额:
/ Update Earnings on User table
func updateEarnings(id: Int, balance: Double) -> Bool {
let updateStatementString = "UPDATE User set balance=? where id=?;"
var updateStatement: OpaquePointer? = nil
if sqlite3_prepare_v2(db,updateStatementString, -1, &updateStatement, nil) == SQLITE_OK {
sqlite3_bind_double(updateStatement, 2, Double(balance))
if sqlite3_step(updateStatement) == SQLITE_DONE {
print("Earnings Updated Successfully.")
sqlite3_finalize(updateStatement)
return true
} else {
print("Could not update.")
return false
}
} else {
print("UPDATE statement is failed.")
return false
}
}
我已经验证了 it 和 balance 的值都是正确的。它返回 true,但 balance 的值从未被传入的值更新。
任何建议都将不胜感激。