How to use SQLx in Rust

Add SQLx with runtime features, create a connection pool, and run async queries to interact with your database in Rust.

Use SQLx in Rust by adding the crate with your database driver and runtime features, then create a connection pool and execute queries asynchronously.

[dependencies]
sqlx = { version = "0.8", features = ["runtime-tokio-rustls", "postgres"] }
tokio = { version = "1.0", features = ["full"] }
use sqlx::postgres::{PgPool, PgPoolOptions};
use std::time::Duration;

#[tokio::main]
async fn main() {
    let db_url = std::env::var("DATABASE_URL").unwrap_or_else(|_| "postgres://postgres:password@localhost".to_string());
    let pool = PgPoolOptions::new()
        .max_connections(5)
        .acquire_timeout(Duration::from_secs(3))
        .connect(&db_url)
        .await
        .expect("Failed to connect");

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

    println!("{result}");
}