Swift Mysql Update语句不起作用

时间:2018-02-12 04:27:24

标签: mysql sqlite

我只是想在我的sqlite数据库上运行一个简单的更新查询,但代码实际上并没有更新数据库中的值,并且它没有抛出指示失败的错误。以下是我正在运行的功能:

func updateItem(nameParam: String, priceParam: String) {
    print("UpdateItem() is running like a dream")
    var db: OpaquePointer?

    let fileURL = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
        .appendingPathComponent("ItemsDatabase.sqlite")

    //opening the database
    if sqlite3_open(fileURL.path, &db) != SQLITE_OK {
        print("error opening database")
    }

    //creating table
    if sqlite3_exec(db, "CREATE TABLE IF NOT EXISTS Items (id INTEGER PRIMARY KEY AUTOINCREMENT, itemName TEXT, itemPrice INTEGER)", nil, nil, nil) != SQLITE_OK {
        let errmsg = String(cString: sqlite3_errmsg(db)!)
        print("error creating table: \(errmsg)")
    }


    //creating a statement
    var stmt: OpaquePointer?

    //the insert query
    let queryString = "UPDATE Items SET itemPrice = ? WHERE itemName = ?"

    //preparing the query
    if sqlite3_prepare(db, queryString, -1, &stmt, nil) != SQLITE_OK{
        let errmsg = String(cString: sqlite3_errmsg(db)!)
        print("error preparing insert: \(errmsg)")
        return
    }

    //binding the parameters
    if sqlite3_bind_text(stmt, 1, priceParam, -1, nil) != SQLITE_OK{
        let errmsg = String(cString: sqlite3_errmsg(db)!)
        print("failure binding name: \(errmsg)")
        return
    }

    if sqlite3_bind_int(stmt, 2, (nameParam as! NSString).intValue) != SQLITE_OK{
        let errmsg = String(cString: sqlite3_errmsg(db)!)
        print("failure binding name: \(errmsg)")
        return
    }

    //executing the query to insert values
    if sqlite3_step(stmt) != SQLITE_DONE {
        let errmsg = String(cString: sqlite3_errmsg(db)!)
        print("failure inserting item: \(errmsg)")
        return
    }

    //displaying a success message
    print("Item successfully edited in the database")
}

我已多次测试输出,并且参数将按预期传递给函数,并且查询准确显示了预期的内容并且似乎是正确的语法。我无法弄清楚是什么导致代码实际上没有更新表,或者失败。

0 个答案:

没有答案