如何使用postgres条板箱处理查询返回的可选值? [英] How to handle an optional value returned by a query using the postgres crate?
问题描述
我正在尝试获取查询的值,但是该值可以为NULL,并且我不知道如何在Rust中处理它。这是我的代码:
I'm trying to get a value for a query, but this value can be NULL and I don't know how to handle it in Rust. Here is my code:
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);
}
当我执行代码时,第一张图片很好,因为评价列不't NULL。但是第二张图片失败了,并给了我 Conversion(WasNull),因为没有评级,我尝试将NULL转换为chrono :: NaiveDate。
When I execute the code, the first picture comes well because the rating column isn't NULL. But the second picture fails and gives me "Conversion(WasNull)", because there is not rating and I try to convert a NULL into a chrono::NaiveDate.
推荐答案
如中所述文档:
可空性
除了类型上面列出的
FromSql
是为
Option< T>
实现的,其中T
实现FromSql
。Option< T>
表示
可为空的Postgres值。
Nullability
In addition to the types listed above,
FromSql
is implemented forOption<T>
whereT
implementsFromSql
. AnOption<T>
represents a nullable Postgres value.
为可以为NULL的字段请求 Option< Type>
;那么该库将自动将NULL转换为 None
:
Request an Option<Type>
for the field that can be NULL; then the library will automatically convert NULL to None
:
let rating: Option<String> = row.get("rating");
这篇关于如何使用postgres条板箱处理查询返回的可选值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!