我正在尝试获取查询的值,但此值可能为NULL,我不知道如何在Rust中处理它。这是我的代码:
let stmt = conn.prepare("SELECT * FROM pictures").unwrap();
for row in stmt.query(&[]).unwrap() {
let id: i32 = row.get("id");
let author: String = row.get("author");
let description: String = row.get("description");
let rating: String = row.get("rating");
let gps_lat: String = row.get("gps_lat");
let gps_long: String = row.get("gps_long");
let date_taken: chrono::NaiveDate = row.get("date_taken");
println!("id -> {}\n
author -> {}\n
description -> {}\n
rating -> {}\n
gps_lat -> {}\n
gps_long -> {}\n
date -> {}\n
", id, author, description, rating, gps_lat, gps_long, date_taken);
}
当我执行代码时,第一张图片很顺利,因为rating列不是NULL。但第二张图片失败并给我“转换(WasNull)”,因为没有评级,我尝试将NULL转换为chrono :: NaiveDate。
答案 0 :(得分:2)
如the documentation中所述:
可空
除了上面列出的类型之外,还实现了
FromSql
Option<T>
其中T
实施FromSql
。Option<T>
代表一个 可贵的Postgres价值。
为可能为NULL的字段请求Option<Type>
;那么库会自动将NULL转换为None
:
let rating: Option<String> = row.get("rating");