【问题标题】:How to handle an optional value returned by a query using the postgres crate?如何使用 postgres crate 处理查询返回的可选值?
【发布时间】:2019-03-30 21:42:12
【问题描述】:

我正在尝试获取查询的值,但该值可以为 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);
}

当我执行代码时,第一张图片很好,因为评级列不为 NULL。但是第二张图片失败并给了我“Conversion(WasNull)”,因为没有评级,我尝试将 NULL 转换为 chrono::NaiveDate。

【问题讨论】:

  • 一个疯狂的猜测:将可以为 NULL 的字段加载为 Options。从你的措辞中我不明白在你的情况下它是 date 还是 rating 可以为 NULL,但如果是后者,它看起来像这样:let rating: Option<String> = row.get("rating");
  • 太棒了!那我把它添加为答案。

标签: postgresql rust


【解决方案1】:

the documentation中所述:

可空性

除了上面列出的类型之外,还实现了FromSql Option<T> 其中T 实现FromSqlOption<T> 代表一个 可为空的 Postgres 值。

为可以为NULL的字段请求Option<Type>;然后库会自动将 NULL 转换为None:

let rating: Option<String> = row.get("rating");

【讨论】:

  • get_opt() 呢?
  • @Tom documentation for get_opt 声明:如果索引未引用列,则返回 None。如果您有一个可能不在行中的可为空列,那么您最终会得到一个Option&lt;Option&lt;T&gt;&gt;
猜你喜欢
  • 1970-01-01
  • 2019-11-14
  • 2019-08-09
  • 1970-01-01
  • 2023-01-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-15
相关资源
最近更新 更多