How to Use sqlx for Async Database Access in Rust

TITLE: How to Use sqlx for Async Database Access in Rust

TITLE: How to Use sqlx for Async Database Access in Rust

Use sqlx with the runtime-tokio-rustls and postgres features to create a connection pool, then inject it into your Axum app via State to execute async queries.

use sqlx::postgres::{PgPool, PgPoolOptions};
use axum::{Router, extract::State};

#[tokio::main]
async fn main() {
    let pool = PgPoolOptions::new()
        .max_connections(5)
        .connect("postgres://postgres:password@localhost")
        .await
        .expect("failed to connect");

    let app = Router::new()
        .route("/", get(handler))
        .with_state(pool);

    axum::serve(tokio::net::TcpListener::bind("127.0.0.1:3000").await.unwrap(), app).await;
}

async fn handler(State(pool): State<PgPool>) -> String {
    let result: String = sqlx::query_scalar("select 'hello'")
        .fetch_one(&pool)
        .await
        .unwrap();
    result
}