d92c1ea9541c477fbed9135c28bc4e12

d92c1ea9541c477fbed9135c28bc4e12

当我将数据插入表(sqlite)时,我正在用t_deleteMsgs编写我的应用程序
ios - SQLite DB-执行结果是什么意思?-LMLPHP
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,然后再次进入vcvc将再次调用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)'")

10-07 22:58