FMDB:NULL 值被检索为空字符串
FMDB: NULL Values Are Retrieved as Empty Strings
我正在使用 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
}
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 is null
您可能需要仔细检查值的插入方式。具体来说,是否使用 NSNull
添加了空值?或者也许在外部工具中打开数据库并验证列是否确实如您预期的那样NULL
。
我正在使用 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
}
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 is null
您可能需要仔细检查值的插入方式。具体来说,是否使用 NSNull
添加了空值?或者也许在外部工具中打开数据库并验证列是否确实如您预期的那样NULL
。