首页 > 解决方案 > 失败准备:插入数据时 SQLite swift 中的错误参数或其他 API 滥用

问题描述

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 滥用

标签: iosswiftsqlite

解决方案


您缺少字符串变量周围的单引号,字符串应该类似于

插入注册详细信息值('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 {
        //...
    }
}

whereusernamepassword是参数发送到insertIntoSignupDetails


推荐阅读