Rust Lesson 51 – Databases | Dataplexa

Database Integration with Rust

In this lesson, you will learn how to connect Rust applications to databases. Database integration is a critical skill for building real-world backend systems, APIs, and services.

Rust provides safe and efficient database libraries that work well with both synchronous and asynchronous applications.


Why Databases Are Important

Databases allow applications to store, retrieve, and manage data persistently. Almost every backend application relies on a database.

Common use cases include:

  • User data storage
  • Application configuration
  • Transaction records
  • Logging and analytics

Popular Databases Used with Rust

Rust works well with many databases, including:

  • PostgreSQL
  • MySQL
  • SQLite
  • NoSQL databases (Redis, MongoDB)

In this lesson, we will focus on PostgreSQL.


Common Rust Database Libraries

Rust has several mature database libraries. The most popular ones are:

  • sqlx – Async, compile-time checked queries
  • Diesel – Powerful ORM with strong typing
  • tokio-postgres – Low-level async client

We will use sqlx because it is modern, async-friendly, and production-ready.


Creating a New Database Project

Create a new Rust project:

cargo new rust_db_app
cd rust_db_app

Adding Dependencies

Add the required dependencies to Cargo.toml.

[dependencies]
sqlx = { version = "0.7", features = ["runtime-tokio", "postgres"] }
tokio = { version = "1", features = ["full"] }

Setting Up the Database Connection

We connect to the database using a connection pool. Pooling improves performance by reusing connections.

use sqlx::postgres::PgPoolOptions;

#[tokio::main]
async fn main() -> Result<(), sqlx::Error> {
    let database_url = "postgres://user:password@localhost/dbname";

    let pool = PgPoolOptions::new()
        .max_connections(5)
        .connect(database_url)
        .await?;

    println!("Connected to database");

    Ok(())
}

This creates a reusable database connection pool.


Creating a Table

Let’s create a simple users table.

CREATE TABLE users (
    id SERIAL PRIMARY KEY,
    name TEXT NOT NULL,
    email TEXT UNIQUE NOT NULL
);

Inserting Data into the Database

Use SQL queries to insert records.

sqlx::query!(
    "INSERT INTO users (name, email) VALUES ($1, $2)",
    "Alice",
    "alice@example.com"
)
.execute(&pool)
.await?;

The query! macro validates SQL at compile time.


Fetching Data from the Database

Retrieve records using SELECT queries.

let users = sqlx::query!(
    "SELECT id, name, email FROM users"
)
.fetch_all(&pool)
.await?;

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

Handling Errors

Rust forces explicit error handling. This prevents silent failures and improves reliability.

match result {
    Ok(data) => println!("Success"),
    Err(e) => println!("Database error: {}", e),
}

Why Rust Is Great for Databases

  • No runtime memory errors
  • Strong compile-time guarantees
  • Excellent async support
  • High performance under load

📝 Practice Exercises


Exercise 1

Create a new table for products.

Exercise 2

Insert multiple records into the database.

Exercise 3

Fetch a single record by ID.


✅ Practice Answers


Answer 1

Define a table with columns such as id, name, and price.

Answer 2

Use multiple INSERT statements or a loop.

Answer 3

Use fetch_one() with a WHERE clause.


What’s Next?

In the next lesson, you will learn how to build Command Line Interface (CLI) applications using Rust.