How to handle an optional value returned by a quer

2019-02-27 20:32发布

问题:

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);
}

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.

回答1:

As described in the documentation:

Nullability

In addition to the types listed above, FromSql is implemented for Option<T> where T implements FromSql. An Option<T> represents a nullable Postgres value.

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");