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:
- MySQL
- PostgreSQL
- SQLite
Important SQLx features:
- Asynchronous database queries.
- Connection pooling.
- Parameterized SQL queries.
- Transactions.
- Mapping database rows into Rust structures.
3. Create a Rust Project
Open your VS Code terminal.
Run:
Your project structure:
4. Install Required Dependencies
Run these commands:
What are these dependencies?
Dependency | Purpose |
|---|---|
| Connect Rust with MySQL |
| Run asynchronous Rust code |
| Read environment variables from a |
5. Create a MySQL Database
Open phpMyAdmin, MySQL Workbench, or your MySQL terminal.
Execute:
Now select the database:
Create a students table:
Insert some sample records:
Your database is ready.
6. Configure MySQL Connection
Create a .env file in your project's root directory.
Replace:
rootwith your MySQL username.passwordwith your MySQL password.localhostwith your database host.3306with your MySQL port.rust_schoolwith your database name.
Important: Never upload your .env file or database credentials to GitHub.
Add this to .gitignore:
7. Connect Rust with MySQL
Open src/main.rs.
Run:
Expected output:
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:
Expected output:
Understanding FromRow
FromRow allows SQLx to convert a database row into a Rust structure.
For example:
SQLx maps the returned columns to the corresponding fields.
9. Fetch a Single Student
Suppose you want to retrieve student ID 1.
Important SQLx Methods
Method | Purpose |
|---|---|
| Retrieve all matching records |
| Retrieve exactly one record |
| Retrieve zero or one record |
| 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.
Understanding bind()
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.
Here:
- First parameter: New fees.
- Second parameter: Student ID.
rows_affected()returns the number of affected rows.
12. Delete a Student – DELETE
To delete student ID 1:
The student with ID 1 will be deleted.
13. Search Students Using LIKE
Suppose you want to find students whose names contain Rah.
The % symbol is a SQL wildcard.
Examples:
Pattern | Meaning |
|---|---|
| Starts with Rah |
| Ends with Rah |
| Contains Rah |
14. Use WHERE, ORDER BY and LIMIT
SQLx supports normal SQL queries.
WHERE
ORDER BY
LIMIT
15. Database Transactions
Transactions allow multiple database operations to be completed together.
Example:
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.
Here:
max_connections(10)sets the maximum number of connections.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.
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 |
|---|---|
| Configure MySQL connection pooling |
| Manage reusable connections |
| Execute SQL statements |
| Map database rows into a Rust type |
| Pass query parameters |
| Retrieve multiple records |
| Retrieve one record |
| Retrieve an optional record |
| Execute a statement |
| Start a transaction |
| Commit a transaction |
| 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 |
|
|
|
|
|
|
|
|
|
|
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
- Connect Rust to your local MySQL database.
- Create a
productstable. - Insert five products using Rust.
- Retrieve all products.
- Search products by name.
- Retrieve a product by ID.
- Update a product price.
- Delete a product.
- Use
ORDER BYandLIMIT. - Create a transaction with multiple SQL queries.
- Connect to a MySQL database hosted on a remote server.