Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
751 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 Reply

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...