let db = Database.openDatabase()
let insertStatementString = "INSERT INTO SignupDetails VALUES (\((self.txtUsername.text!.trimmingCharacters(in: .whitespaces))), \((self.txtPassword.text!.trimmingCharacters(in: .whitespaces))))"
Database.insertIntoSignupDetails(db: db, insertStatementString: insertStatementString)
sqlite3_close(db)
上面的代码包含我使用sqlite将数据插入数据库的查询。
我创建了一个表格,如下所示:-
let db = Database.openDatabase()
let createTableString =
"""
CREATE TABLE IF NOT EXISTS SignupDetails(
username CHAR(255),
password CHAR(255));
"""
Database.createTable(db: (db != nil) ? db : OpaquePointer(UserDefaults.standard.object(forKey: Constant.db) as! String), createTableString: createTableString)
sqlite3_close(db)
并且我还成功执行了以下代码以创建表:-
static func createTable(db: OpaquePointer?, createTableString: String) {
var createTableStatement: OpaquePointer? = nil
if sqlite3_prepare_v2(db, createTableString, -1, &createTableStatement, nil) == SQLITE_OK {
if sqlite3_step(createTableStatement) == SQLITE_DONE {
print("table created.")
} else {
print("table could not be created.")
}
} else {
print("CREATE TABLE statement could not be prepared.")
}
sqlite3_finalize(createTableStatement)
}
但是我的问题是当我试图将数据插入到现有表中时
显示错误如下:-
代码:-
var insertStatement: OpaquePointer?
guard sqlite3_prepare_v2(db, insertStatementString, -1, &insertStatement, nil) == SQLITE_OK else {
let errmsg = String(cString: sqlite3_errmsg(db))
print("failure preparing: \(errmsg)")
return
}
if sqlite3_step(insertStatement) == SQLITE_OK {
print("Successfully inserted row.")
} else {
print("Could not insert row.")
}
sqlite3_finalize(insertStatement)
错误:-
准备失败:参数错误或其他API滥用
答案 0 :(得分:0)
您缺少字符串变量周围的单引号,字符串应类似于
插入SignupDetails值('gopabandhu@bt.com','123')
let insertStatementString = "INSERT INTO SignupDetails VALUES ('\((self.txtUsername.text!.trimmingCharacters(in: .whitespaces)))', '\((self.txtPassword.text!.trimmingCharacters(in: .whitespaces)))')"
另一种选择是在语句中使用占位符
let statement = "INSERT INTO SignupDetails(username, password) VALUES (?, ?)"
if sqlite3_prepare_v2(db, insertStatementString, -1, &insertStatement, nil) == SQLITE_OK {
sqlite3_bind_text(insertStatement, 1, username.utf8String, -1, nil)
sqlite3_bind_text(insertStatement, 2, password.utf8String, -1, nil)
if sqlite3_step(insertStatement) == SQLITE_OK {
//...
}
}
其中username
和password
是发送到insertIntoSignupDetails
的参数