Rust, Software Development

Rust – Connect to MySQL And Query For Data

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

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

5 Comments

  1. 1

    Thank you for sharing.

    Under Rust Codes in your post you make reference to Postgres, is not supposed to be Mysql?

  2. 2
  3. 3

    I’m new to Rust and wanted to see how it worked with MySQL so thanks for your tutorial. I have one problem, it fails when compiling on line 119 of dbghelp.rs – error: expected an item keyword (let function_table_access = dbghelp.SymFunctionTableAccess64();).
    Have I missed something obvious setting up Rust environment? My database is a remote database hosted on my website, if that makes any difference?

  4. 4

    Are you using crates with the same versions as in the post? Perhaps SysFunctionTableAccess64 is missing? Do you have the codes in public github repo?

  5. 5

    Thanks for the reply – my mistake had put ‘MySQL = “*”‘ in dependencies, changed to MySQL = “16.1.0” and now working perfectly. Thanks again for sharing original code.

Comments are closed.