Swift 4 SQLITE查询输出失败,带有where子句

时间:2018-03-17 01:03:25

标签: sql swift sqlite filter

我是iOS和SWIFT的新手但取得了进步。

我使用SQLITE数据库来存储员工详细信息。在查询数据时,我需要使用WHERE子句过滤输出,将其限制为只有一行。查询不提供任何输出,但如果我删除WHERE子句,它可以工作。我需要能够将查询输出过滤到用户的特定i-phone。

这是我在App中许多地方使用的类中的静态函数。 我的代码:

// ***********************************
static func queryPhoneOwner() {
     let queryPhoneOwnerString = "SELECT EMPLOYEE_ID, FULL_NAME, LOCATION, UUID FROM MT_PHONE_OWNER WHERE UUID = ?"
    var queryPhoneOwnerStatement: OpaquePointer? = nil
    let db = DatabaseClass.openDatabase()
    var vUUID: String = " "
    if sqlite3_prepare_v2(db, queryPhoneOwnerString, -1, &queryPhoneOwnerStatement, nil) == SQLITE_OK {

        if let uuid = UIDevice.current.identifierForVendor?.uuidString {

            vUUID = uuid
        }

         sqlite3_bind_text(queryPhoneOwnerStatement, 1, vUUID, -1, nil)

        while (sqlite3_step(queryPhoneOwnerStatement) == SQLITE_ROW) {

            let queryResultCol1 = sqlite3_column_text(queryPhoneOwnerStatement, 0)
            let vOwnerEmployeeId = String(cString: queryResultCol1!)

            let queryResultCol2 = sqlite3_column_text(queryPhoneOwnerStatement, 1)
            let vOwnerFullName = String(cString: queryResultCol2!)

            let queryResultCol3 = sqlite3_column_text(queryPhoneOwnerStatement, 2)
            let vOwnerLocation = String(cString: queryResultCol3!)

            let queryResultCol4 = sqlite3_column_text(queryPhoneOwnerStatement, 3)
            let vOwnerUuid = String(cString: queryResultCol4!)

// and the code continues..
// FYI, Table columns pasted here from table creation process: "CREATE TABLE IF NOT EXISTS MT_PHONE_OWNER (EMPLOYEE_ID VARCHAR(10) PRIMARY KEY, FULL_NAME VARCHAR(50), LOCATION VARCHAR(15), UUID VARCHAR2(45) NOT NULL)"
//********************************************

1 个答案:

答案 0 :(得分:1)

  1. 避免在代码中使用SELECT * FROM。明确列出您要查询的字段。这可确保您按特定顺序获取特定值,这对于sqlite3_column_text用法非常重要。
  2. 您的查询有一个参数。这意味着您的sqlite3_bind_text索引必须匹配。您正在传递4,但需要1
  3. 并非真正的问题,但?并不需要在查询的括号中。
  4. 小心展开sqlite3_column_text的结果。数据库中可能有NULL值,这就是结果是可选的。如果该列设置为NOT NULL,那么这可能正常,因为该值永远不会是nil