swift错误:执行被中断,原因:EXC_BAD_INSTRUCTION(代码= EXC_I386_INVOP,子代码= 0x0)

时间:2018-01-14 20:36:43

标签: swift sqlite exc-bad-instruction

我搜索错误,但我找不到我理解的答案。我是斯威夫特的新手,所以请善待。 当我尝试在数据库中插入名称时,出现错误[执行被中断]。打开数据库并创建表是没有问题的。

let insertStatementString = "INSERT INTO Contact (Id, Name) VALUES (?, ?);"

func insert(name: String) {
    var insertStatement: OpaquePointer? = nil

    // 1
    if sqlite3_prepare_v2(db, insertStatementString, -1, &insertStatement, nil) == SQLITE_OK {
        let MaxIdQuery: String = "SELECT max(Id) from Contact"

        var id: Int32 = 0
        id =  Int32(query(queryStatementString: MaxIdQuery))!
        print("Id = ", id.description)

        // 2
        sqlite3_bind_int(insertStatement, 1, id)
        // 3
        sqlite3_bind_text(insertStatement, 2, name, -1, nil)

        // 4
        if sqlite3_step(insertStatement) == SQLITE_DONE {
            print("Successfully inserted row.")
        } else {
            print("Could not insert row.")
        }
    } else {
        print("INSERT statement could not be prepared.")
    }
    // 5
    sqlite3_finalize(insertStatement)
}

func query(queryStatementString: String) -> String {

    let Result: String = ""
    var queryStatement: OpaquePointer? = nil
    // 1
    if sqlite3_prepare_v2(db, queryStatementString, -1, &queryStatement, nil) == SQLITE_OK {
        // 2
        if sqlite3_step(queryStatement) == SQLITE_ROW {
            // 3
            let id = sqlite3_column_int(queryStatement, 0)

            // 4
            let queryResultCol1 = sqlite3_column_text(queryStatement, 1)
            let name = String(cString: queryResultCol1!)

            // 5
//            print("Query Result:")
            let Result = "\(id) | \(name)"

        } else {
            let Result = "Query returned no results"
        }
    } else {
        let Result = "SELECT statement could not be prepared"
    }

    // 6
    sqlite3_finalize(queryStatement)
    print("Result:" + Result)
    return Result
}

insert(name: "Ray")  //this is where the error occurs.

//错误:游乐场执行中止:错误:执行被中断,原因:EXC_BAD_INSTRUCTION(代码= EXC_I386_INVOP,子代码= 0x0)

我发现了错误。 在'insert()'里面,我查询最高'id'并且在'query()里面。 Query()应该填充两个变量(id和name)。查询'SELECT max(Id)from Contact'只传递一个值。所以query()中的name-variable为空,导致错误。

0 个答案:

没有答案