Rust
December 2, 2026 8 min read

Database Connectivity in Rust Using MySQL

HS
HEMANT SINGH
Technical Writer & Educator

1. Introduction

MySQL is a relational database management system (RDBMS).

It stores data in tables containing rows and columns.

For example, a student management system may have a students table.


id

name

course

fees

1

Rahul

ADCA

5000

2

Amit

Python

4000

3

Priya

Rust

6000

Rust can communicate with MySQL using database libraries.

In this lesson, we will use SQLx.

2. What is SQLx?

SQLx is a Rust library for working with SQL databases.

It supports:

  1. MySQL
  2. PostgreSQL
  3. SQLite

Important SQLx features:

  1. Asynchronous database queries.
  2. Connection pooling.
  3. Parameterized SQL queries.
  4. Transactions.
  5. Mapping database rows into Rust structures.

3. Create a Rust Project

Open your VS Code terminal.

Run:

cargo new rust_mysql
cd rust_mysql
code .

Your project structure:

rust_mysql/
│
├── Cargo.toml
│
└── src/
└── main.rs

4. Install Required Dependencies

Run these commands:

cargo add sqlx --features runtime-tokio,mysql,derive
cargo add tokio --features macros,rt-multi-thread
cargo add dotenvy

What are these dependencies?


Dependency

Purpose

sqlx

Connect Rust with MySQL

tokio

Run asynchronous Rust code

dotenvy

Read environment variables from a .env file

5. Create a MySQL Database

Open phpMyAdmin, MySQL Workbench, or your MySQL terminal.

Execute:

CREATE DATABASE rust_school;

Now select the database:

USE rust_school;

Create a students table:

CREATE TABLE students (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100) NOT NULL,
course VARCHAR(100) NOT NULL,
fees DECIMAL(10,2) NOT NULL
);

Insert some sample records:

INSERT INTO students (name, course, fees)
VALUES
('Rahul', 'ADCA', 5000),
('Amit', 'Python', 4000),
('Priya', 'Rust', 6000);

Your database is ready.

6. Configure MySQL Connection

Create a .env file in your project's root directory.

DATABASE_URL=mysql://root:password@localhost:3306/rust_school

Replace:

  1. root with your MySQL username.
  2. password with your MySQL password.
  3. localhost with your database host.
  4. 3306 with your MySQL port.
  5. rust_school with your database name.

Important: Never upload your .env file or database credentials to GitHub.

Add this to .gitignore:

.env

7. Connect Rust with MySQL

Open src/main.rs.

use sqlx::mysql::MySqlPoolOptions;
use std::env;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {

dotenvy::dotenv().ok();

let database_url = env::var("DATABASE_URL")?;

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

println!("MySQL connected successfully!");

pool.close().await;

Ok(())
}

Run:

cargo run

Expected output:

MySQL connected successfully!

Understanding the Code

MySqlPoolOptions

Creates and configures a MySQL connection pool.

max_connections(5)

Allows the pool to maintain up to five connections.

connect()

Connects to the MySQL database.

await

Waits for the asynchronous database operation.

pool.close()

Closes the connection pool.

8. Fetch All Students – SELECT

Now let's retrieve all students from MySQL.

Replace your main.rs with:

use sqlx::mysql::MySqlPoolOptions;
use sqlx::FromRow;
use std::env;

#[derive(Debug, FromRow)]
struct Student {
id: i32,
name: String,
course: String,
fees: f64,
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {

dotenvy::dotenv().ok();

let database_url = env::var("DATABASE_URL")?;

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

let students = sqlx::query_as::<_, Student>(
"SELECT id, name, course, fees FROM students"
)
.fetch_all(&pool)
.await?;

for student in students {
println!("{:?}", student);
}

Ok(())
}

Expected output:

Student { id: 1, name: "Rahul", course: "ADCA", fees: 5000.0 }
Student { id: 2, name: "Amit", course: "Python", fees: 4000.0 }
Student { id: 3, name: "Priya", course: "Rust", fees: 6000.0 }

Understanding FromRow

#[derive(Debug, FromRow)]

FromRow allows SQLx to convert a database row into a Rust structure.

For example:

struct Student {
id: i32,
name: String,
course: String,
fees: f64,
}

SQLx maps the returned columns to the corresponding fields.

9. Fetch a Single Student

Suppose you want to retrieve student ID 1.

let student = sqlx::query_as::<_, Student>(
"SELECT id, name, course, fees FROM students WHERE id = ?"
)
.bind(1)
.fetch_one(&pool)
.await?;

println!("{:?}", student);

Important SQLx Methods


Method

Purpose

fetch_all()

Retrieve all matching records

fetch_one()

Retrieve exactly one record

fetch_optional()

Retrieve zero or one record

execute()

Execute INSERT, UPDATE, or DELETE queries

If no row exists, fetch_one() returns an error. Use fetch_optional() when a missing record is an expected possibility.

10. Insert a Student – CREATE

Let's insert a new student.

let result = sqlx::query(
"INSERT INTO students (name, course, fees)
VALUES (?, ?, ?)"
)
.bind("Hemant")
.bind("Rust Programming")
.bind(7000.0)
.execute(&pool)
.await?;

println!("Student inserted successfully!");

println!("New ID: {}", result.last_insert_id());

Understanding bind()

.bind("Hemant")
.bind("Rust Programming")
.bind(7000.0)

These values are supplied to the SQL placeholders in order.

Parameterized queries help protect your application from SQL injection.

11. Update a Student – UPDATE

Suppose you want to change the fees of student ID 1.

let result = sqlx::query(
"UPDATE students SET fees = ? WHERE id = ?"
)
.bind(6000.0)
.bind(1)
.execute(&pool)
.await?;

println!("Updated rows: {}", result.rows_affected());

Here:

  1. First parameter: New fees.
  2. Second parameter: Student ID.
  3. rows_affected() returns the number of affected rows.

12. Delete a Student – DELETE

To delete student ID 1:

let result = sqlx::query(
"DELETE FROM students WHERE id = ?"
)
.bind(1)
.execute(&pool)
.await?;

println!("Deleted rows: {}", result.rows_affected());

The student with ID 1 will be deleted.

13. Search Students Using LIKE

Suppose you want to find students whose names contain Rah.

let search = "%Rah%";

let students = sqlx::query_as::<_, Student>(
"SELECT id, name, course, fees
FROM students
WHERE name LIKE ?"
)
.bind(search)
.fetch_all(&pool)
.await?;

for student in students {
println!("{:?}", student);
}

The % symbol is a SQL wildcard.

Examples:


Pattern

Meaning

Rah%

Starts with Rah

%Rah

Ends with Rah

%Rah%

Contains Rah

14. Use WHERE, ORDER BY and LIMIT

SQLx supports normal SQL queries.

WHERE

let students = sqlx::query_as::<_, Student>(
"SELECT * FROM students WHERE fees > ?"
)
.bind(5000.0)
.fetch_all(&pool)
.await?;

ORDER BY

let students = sqlx::query_as::<_, Student>(
"SELECT * FROM students ORDER BY fees DESC"
)
.fetch_all(&pool)
.await?;

LIMIT

let students = sqlx::query_as::<_, Student>(
"SELECT * FROM students LIMIT 5"
)
.fetch_all(&pool)
.await?;

15. Database Transactions

Transactions allow multiple database operations to be completed together.

Example:

let mut tx = pool.begin().await?;

sqlx::query(
"UPDATE students SET fees = fees + 500 WHERE id = ?"
)
.bind(1)
.execute(&mut *tx)
.await?;

sqlx::query(
"UPDATE students SET fees = fees - 500 WHERE id = ?"
)
.bind(2)
.execute(&mut *tx)
.await?;

tx.commit().await?;

If an error occurs before commit(), dropping the transaction rolls it back.

Transactions are useful when multiple operations must succeed or fail together.

16. Use Connection Pooling

A connection pool maintains reusable database connections.

let pool = MySqlPoolOptions::new()
.max_connections(10)
.min_connections(2)
.connect(&database_url)
.await?;

Here:

  1. max_connections(10) sets the maximum number of connections.
  2. min_connections(2) sets the minimum number of connections to maintain.

Connection pooling is useful in applications where many requests access the database.

17. Complete CRUD Example

This example combines the four basic database operations.

use sqlx::mysql::MySqlPoolOptions;
use sqlx::FromRow;
use std::env;

#[derive(Debug, FromRow)]
struct Student {
id: i32,
name: String,
course: String,
fees: f64,
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {

dotenvy::dotenv().ok();

let database_url = env::var("DATABASE_URL")?;

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

// CREATE
sqlx::query(
"INSERT INTO students (name, course, fees)
VALUES (?, ?, ?)"
)
.bind("Karan")
.bind("Rust")
.bind(8000.0)
.execute(&pool)
.await?;

println!("Student inserted!");

// READ
let students = sqlx::query_as::<_, Student>(
"SELECT id, name, course, fees FROM students"
)
.fetch_all(&pool)
.await?;

println!("\nStudent Records:");

for student in students {
println!(
"{} | {} | {} | {}",
student.id,
student.name,
student.course,
student.fees
);
}

// UPDATE
sqlx::query(
"UPDATE students SET fees = ? WHERE id = ?"
)
.bind(9000.0)
.bind(1)
.execute(&pool)
.await?;

println!("\nStudent updated!");

// DELETE
sqlx::query(
"DELETE FROM students WHERE id = ?"
)
.bind(2)
.execute(&pool)
.await?;

println!("Student deleted!");

pool.close().await;

Ok(())
}

Note: This example inserts a new student each time it runs. It also uses fixed IDs for demonstration. In a real application, use the actual inserted ID and check that records exist before updating or deleting them.

18. Important SQLx Concepts


Concept

Purpose

MySqlPoolOptions

Configure MySQL connection pooling

MySqlPool

Manage reusable connections

query()

Execute SQL statements

query_as()

Map database rows into a Rust type

bind()

Pass query parameters

fetch_all()

Retrieve multiple records

fetch_one()

Retrieve one record

fetch_optional()

Retrieve an optional record

execute()

Execute a statement

begin()

Start a transaction

commit()

Commit a transaction

rows_affected()

Get the affected row count

19. SQLx vs Laravel Eloquent

Since Laravel uses Eloquent ORM, it is useful to understand the difference.


Laravel

Rust SQLx

Eloquent ORM

SQL query-based database library

Model

Rust struct

Model::all()

fetch_all()

Model::find($id)

fetch_optional() with a WHERE query

Model::create()

INSERT with execute()

$model->update()

UPDATE with execute()

$model->delete()

DELETE with execute()

Database transactions

SQLx transactions

SQLx is not an equivalent replacement for Eloquent. It is primarily a SQL toolkit with database access and mapping features.

20. Practice Exercises

  1. Connect Rust to your local MySQL database.
  2. Create a products table.
  3. Insert five products using Rust.
  4. Retrieve all products.
  5. Search products by name.
  6. Retrieve a product by ID.
  7. Update a product price.
  8. Delete a product.
  9. Use ORDER BY and LIMIT.
  10. Create a transaction with multiple SQL queries.
  11. Connect to a MySQL database hosted on a remote server.