Rust, Software Development

CRUD Operations with Rust Rocket SQLX with MySQL

This post shows how to use Rust Rocket SQLX for MySQL for basic CRUD (Create, Retrieve, Update, and Delete) operations.

Prerequisites For Building the Rust Application Based on Rocket

We used the following items for this post.

  1. Rust Stable – 1.64.0
  2. Rocket 0.5.0-rc.2
  3. Windows 10
  4. Docker For Windows
  5. MySQL 8
  6. IntelliJ IDEA 2022.2.3 (Ultimate Edition)
  7. Rust Plugin for IntelliJ

Before running Rust Rocket SQLX codes against MySQL 8, we need to start an instance of that database, which we can have in the form of a Docker container. For more information, please see docker-compose.yml for MySQL For Local Development. Also, we will use the same database credentials in this Rust application.

Essential Crate Dependencies for Rust, Rocket, and SQLX

Although we are using a release candidate of Rocket, the final release (0.5) would still be compatible with our codes. We will tweak the codes if we need to adjust something. Generally, the codes would still work.

Our Cargo.toml file has the following dependencies.

We need a Rocket.toml For Rocket and SQLX

To work with SQLX within Rocket, we need the specify the database properties in another file – Rocket.toml. We can specify the connection string, database credentials, and connection-related properties in this file.

Next, we need to create the following struct and label it “alertodb” using the database attribute.

Then, use that struct in our main function to invoke the init function.

Rust Rocket HTTP Handlers with SQLX Database Connection

Where do we get our database connection? We must pass it as a parameter to our HTTP handler functions to work with a database connection. Consider the following codes.

Then, in our DAO layer (if it makes sense in Rust lang), we use the database connection as shown in the following codes.

That’s how we can use Rust Rocket SQLX for MySQL for basic CRUD (Create, Retrieve, Update, and Delete) operations.

Loading

Got comments or suggestions? We disabled the comments on this site to fight off spammers, but you can still contact us via our Facebook page!.


You Might Also Like