Skip to content

Rust Database — SQL Database Access with SQLx and Diesel for PostgreSQL

DodaTech Updated 2026-06-28 1 min read

In this tutorial, you will learn about Rust Database. We cover key concepts, practical examples, and best practices to help you master this topic.

Rust database access uses SQLx for async compile-time checked SQL and Diesel for ORM-based schema management with PostgreSQL, MySQL, and SQLite.

What You'll Learn

  • SQLx async queries
  • Diesel ORM
  • Migration management
  • Connection pooling

Why It Matters

Database access is essential for Web Services. DodaZIP uses SQLx for metadata storage.

Real-World Use

Web application backends, data processing pipelines, analytics services.

use sqlx::postgres::PgPoolOptions;
use sqlx::FromRow;

#[derive(FromRow, Debug)]
struct User {
    id: i32,
    name: String,
    email: String,
}

#[tokio::main]
async fn main() -> Result<(), sqlx::Error> {
    let pool = PgPoolOptions::new()
        .max_connections(5)
        .connect("postgres://user:pass@localhost/db")
        .await?;

    // Query
    let users: Vec<User> = sqlx::query_as("SELECT * FROM users")
        .fetch_all(&pool)
        .await?;

    for user in users {
        println!("{}: {} ({})", user.id, user.name, user.email);
    }

    // Insert
    let user = sqlx::query_as::<_, User>(
        "INSERT INTO users (name, email) VALUES ($1, $2) RETURNING *"
    )
    .bind("Alice")
    .bind("alice@test.com")
    .fetch_one(&pool)
    .await?;

    println!("Created: {:?}", user);

    // Transaction
    let mut tx = pool.begin().await?;
    sqlx::query("UPDATE users SET name = $1 WHERE id = $2")
        .bind("Bob")
        .bind(1i32)
        .execute(&mut *tx)
        .await?;
    tx.commit().await?;

    Ok(())
}

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro