当我将数据插入表(sqlite
)时,我正在用t_deleteMsgs
编写我的应用程序
在initData()
中:
db = SQLiteDB.sharedInstance
let result = db.execute(sql: "create table if not exists t_deleteMsg(uid integer primary key, msg_userId varchar(20), msg_id varchar(20))") // if not exists
print(result)
注意:
结果打印
1
,表示成功:这是
execute
方法:// Execute SQL with parameters and return result code
func execute(sql:String, parameters:[Any]?=nil)->CInt {
var result:CInt = 0
queue.sync() {
if let stmt = self.prepare(sql:sql, params:parameters) {
result = self.execute(stmt:stmt, sql:sql)
}
}
return result
}
以及
self.execute
:private func execute(stmt:OpaquePointer, sql:String)->CInt {
// Step
var result = sqlite3_step(stmt)
if result != SQLITE_OK && result != SQLITE_DONE {
sqlite3_finalize(stmt)
if let error = String(validatingUTF8:sqlite3_errmsg(self.db)) {
let msg = "SQLiteDB - failed to execute SQL: \(sql), Error: \(error)"
NSLog(msg)
}
return 0
}
// Is this an insert
let upp = sql.uppercased()
if upp.hasPrefix("INSERT ") {
// Known limitations: http://www.sqlite.org/c3ref/last_insert_rowid.html
let rid = sqlite3_last_insert_rowid(self.db)
result = CInt(rid)
} else if upp.hasPrefix("DELETE") || upp.hasPrefix("UPDATE") {
var cnt = sqlite3_changes(self.db)
if cnt == 0 {
cnt += 1
}
result = CInt(cnt)
} else {
result = 1
}
// Finalize
sqlite3_finalize(stmt)
return result
}
在我的vc中创建表,然后将数据插入表中:
func saveDeleteMsgToDB(userId:String , deleteId:String) {
let sql = "insert into t_deleteMsgs(msg_userId, msg_id) values('\(userId)', '\(deleteId)')"
print("sql:\(sql)")
// 通过封装的方法执行sql
let result = db.execute(sql: sql)
print(result)
}
结果:打印结果:
2
。我不知道2
是什么意思,你可以在前面看到我的self.execute
方法,如果是插入成功?所以,我弹出
vc
,然后再次进入vc
,vc
将再次调用initDeleteArr()
: func initDeleteArr() {
let userStatic:UserStaticSwift = UserStaticSwift.sharedInstance()
let data = db.query(sql: "select * from t_deleteMsgs where msg_userId = \(userStatic.userId)") // here the data's count is 0.
if data.count > 0 {
let delete_msg = data[data.count - 1]
print(delete_msg)
}
}
在
initDeleteArr()
中:SQLiteDB-未能准备SQL:select*from t_deleteMsgs where msg_userId=d92c1ea9541c477fbed9135c28bc4e12,错误:没有此类列:d92c1ea9541c477fbed9135c28bc4e12
那么,如果插入数据失败,这里的问题在哪里?
最佳答案
SQL表达式无效:select * from t_deleteMsgs where msg_userId = d92c1ea9541c477fbed9135c28bc4e12
,因为它将查找名为d92c1ea9541c477fbed9135c28bc4e12的列。用'
转义此字符串,它应该可以工作:select * from t_deleteMsgs where msg_userId = 'd92c1ea9541c477fbed9135c28bc4e12'
,
所以在你的代码中:
let data = db.query(sql: "select * from t_deleteMsgs where msg_userId = '\(userStatic.userId)'")