Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
795 views
in Technique[技术] by (71.8m points)

postgresql - How to handle an optional value returned by a query using the postgres crate?

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        -> {}

           author      -> {}

           description -> {}

           rating      -> {}

           gps_lat     -> {}

           gps_long    -> {}

           date        -> {}

       ", 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...