SQLiteDB - 执行结果的意思是什么?

时间:2017-01-19 08:23:53

标签: ios swift sqlite

当我将数据插入表格(sqlite

时,我正在用t_deleteMsgs编写我的应用程序

enter image description here

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)  

注意:

结果print 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其中msg_userId = d92c1ea9541c477fbed9135c28bc4e12,错误:没有这样的列:d92c1ea9541c477fbed9135c28bc4e12

那么,这里的问题在哪里,我是否插入数据失败?

1 个答案:

答案 0 :(得分:0)

您的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)'")