我对Xcode相当陌生,尤其是Xcode中的sqlite,我收到一个错误,我不知道如何解决。我已经在Xcode之外使用SQLite和类似Python的语言,但是它的工作方式与此不同。
import UIKit
import SQLite3
class ViewController: UIViewController, UITextFieldDelegate {
var db: OpaquePointer?
override func viewDidLoad() {
super.viewDidLoad()
let fileUrl = try!
FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false).appendingPathComponent("testDB.sqlite3")
if sqlite3_open(fileUrl.path, &db) != SQLITE_OK{
print("Error opening database.")
return
}
let createTableQuery = "CREATE TABLE IF NOT EXISTS test (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, strength TEXT)"
if sqlite3_exec(db, createTableQuery, nil, nil, nil) != SQLITE_OK{
print("Error creating table.")
return
}
print("Database created.")
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
self.view.endEditing(true)
}
//Properties
@IBOutlet weak var inputName: UITextField!
@IBOutlet weak var inputStrength: UITextField!
//Action
@IBAction func buttonConfirm(_ sender: Any) {
let name = inputName.text?.trimmingCharacters(in: .whitespacesAndNewlines)
let strength = inputStrength.text?.trimmingCharacters(in: .whitespacesAndNewlines)
if(name?.isEmpty)!{
print("Name is empty.")
return;
}
if(strength?.isEmpty)!{
print("Strength is empty.")
return;
}
var stmt: OpaquePointer?
let insertQuery = "INSERT INTO testDB (name, strength) VALUES(?, ?);"
if sqlite3_prepare(db, insertQuery, -1, &stmt, nil) != SQLITE_OK{
print("Error binding query.")
}
if sqlite3_bind_text(stmt, 1, name, -1, nil) != SQLITE_OK{
print("Error binding name.")
}
if sqlite3_bind_text(stmt, 2, strength, -1, nil) != SQLITE_OK{
print("Error binding strength.")
}
if sqlite3_step(stmt) == SQLITE_DONE{
print("Values saved successfully.")
}
}
}
我的大多数错误是“没有用空准备语句调用API”,没有任何查询绑定。
Database created.
Error binding query.
2019-11-20 09:32:18.381316+0000 PharmAssist[27925:1197718] [logging] API called with NULL prepared statement
2019-11-20 09:32:18.381453+0000 PharmAssist[27925:1197718] [logging] misuse at line 89232 of [378230ae7f]
Error binding name.
2019-11-20 09:32:18.381601+0000 PharmAssist[27925:1197718] [logging] API called with NULL prepared statement
2019-11-20 09:32:18.381719+0000 PharmAssist[27925:1197718] [logging] misuse at line 89232 of [378230ae7f]
Error binding strength.
2019-11-20 09:32:18.381835+0000 PharmAssist[27925:1197718] [logging] API called with NULL prepared statement
2019-11-20 09:32:18.381933+0000 PharmAssist[27925:1197718] [logging] misuse at line 88645 of [378230ae7f]
Message from debugger: Terminated due to signal 15
更正您的数据库和表名