我搜索错误,但没有找到我理解的答案。我是 Swift 的新手,所以请善待。当我尝试在数据库中插入名称时出现错误 [执行被中断]。打开数据库并创建表是没有问题的。
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.
//error: Playground execution aborted: error: 执行被中断,原因:EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)
我发现了错误。在“插入()”内部,我查询最高的“id”,即在“查询()”内部。Query() 应该填充两个变量(id 和 name)。查询 'SELECT max(Id) from Contact" 只提供一个值。因此 query() 中的名称变量为空,这会导致错误。