【问题标题】:FMDB: NULL Values Are Retrieved as Empty StringsFMDB:NULL 值作为空字符串检索
【发布时间】:2015-08-03 13:37:09
【问题描述】:

我正在使用下面的(简化的)函数通过 FMDB 和 Swift 检索客户记录。当title列中的可选值为NULL时,返回的客户对象的title成员是一个空字符串而不是nil,这是一种误导。 是否可以重写,以便将 NULL 值检索为 nil -- 理想情况下不测试空字符串并显式设置 nil(如果该值实际上是空字符串)?

func getCustomerById(id: NSUUID) -> Customer? {

    let db = FMDatabase(path: dbPath as String)
    if db.open() {
        let queryStatement = "SELECT * FROM Customers WHERE id = ?"
        let result = db.executeQuery(queryStatement, withArgumentsInArray: [id.UUIDString])

        while result.next() {
            var customer = Customer();
            customer.id = NSUUID(UUIDString: result.stringForColumn("customerId"))
            customer.firstName = result.stringForColumn("firstName")
            customer.lastName = result.stringForColumn("lastName")
            customer.title = result.stringForColumn("title")
            return customer
        }
    }
    else {
        println("Error: \(db.lastErrorMessage())")
    }
    return nil
}

【问题讨论】:

  • source code 我会假设一个NULL值返回为nil
  • 我以为我检查了数据库。再次检查 - 你是对的。我很尴尬。

标签: ios swift sqlite fmdb


【解决方案1】:

NULL 值返回为nil

db.executeUpdate("create table foo (bar text)", withArgumentsInArray: nil)
db.executeUpdate("insert into foo (bar) values (?)", withArgumentsInArray: ["baz"])
db.executeUpdate("insert into foo (bar) values (?)", withArgumentsInArray: [NSNull()])

if let rs = db.executeQuery("select * from foo", withArgumentsInArray: nil) {
    while rs.next() {
        if let string = rs.stringForColumn("bar") {
            println("bar = \(string)")
        } else {
            println("bar is null")
        }
    }
}

输出:

bar = baz
bar 为空

您可能需要仔细检查值的插入方式。具体来说,是否使用NSNull 添加了空值?或者也许在外部工具中打开数据库并验证这些列是否真的像您预期的那样NULL

【讨论】:

  • 你是对的,新记录确实是这样插入的。我一定是在查看一些错误添加的旧数据。谢谢你在这里解释。我会留下这个问题,因为您的回答可能对其他人有用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-03
  • 1970-01-01
  • 2019-03-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多