How to use sqlx crate in Rust async SQL

Initialize a SQLx connection pool with tokio runtime features and execute async queries using .await.

Use sqlx with tokio runtime features to create a connection pool and execute queries asynchronously. Add sqlx with runtime-tokio-rustls and your database driver to Cargo.toml, then initialize a PgPool and run queries using .await.

use sqlx::postgres::{PgPool, PgPoolOptions};
use std::time::Duration;

#[tokio::main]
async fn main() {
    let pool = PgPoolOptions::new()
        .max_connections(5)
        .acquire_timeout(Duration::from_secs(3))
        .connect("postgres://postgres:password@localhost")
        .await
        .expect("can't connect to database");

    let result: String = sqlx::query_scalar("select 'hello world from pg'")
        .fetch_one(&pool)
        .await
        .expect("query failed");

    println!("{result}");
}