How to connect to PostgreSQL from Rust

Connect to PostgreSQL from Rust by adding the tokio-postgres dependency and calling Client::connect with your database URL.

Add the tokio-postgres crate to your dependencies and use Client::connect to establish a connection with your database URL.

[dependencies]
tokio-postgres = "0.7"
use tokio_postgres::{NoTls, Client, Error};

#[tokio::main]
async fn main() -> Result<(), Error> {
    let (client, connection) = tokio_postgres::connect("host=localhost user=postgres password=secret dbname=mydb", NoTls).await?;
    tokio::spawn(async move {
        if let Err(e) = connection.await {
            eprintln!("connection error: ", e);
        }
    });
    Ok(())
}