Rust, Software Development

Rust – Connect to MySQL And Query For Data

This post is about connecting to MySQL from Rust and querying data.

Contents

Rust Requirements Using the MySQL Crate

MySQL Database Table To Query Data

We have this table structure for our codes and testing.

Sample data:

Update Cargo.toml With Crate That Can Connect To And Query Data from MySQL

Under the [dependencies] section, add the mysql = "16.1.0" :

Rust Codes To Connect To And Run Query against MySQL

Before we create the codes to connect to MySQL and retrieve it, we need to reference the MySQL crate.

Then, we need to create a struct that resembles and represents the persons table.

In the main function, we first get a connection:

Note that we are passing both the database user name and password. With a database connection, we can now retrieve records from the persons table.

Finally, we test the application. When we run our application, we get the following output.

And that’s how we connect to MySQL from Rust and query for data! We tested the codes using Rust 1.37.0.

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