This post is about connecting to MySQL from Rust and querying data.
Rust Requirements Using the MySQL Crate
- Cargo
- A Rust package manager akin to Apache Maven
- It also gets installed when we install Rust with rustup-init.exe
- A Rust crate called mysql
- A running instance of MySQL
MySQL Database Table To Query Data
We have this table structure for our codes and testing.
1 2 3 4 5 6 7 | create table person ( person_id int auto_increment, person_name varchar(100) null, constraint person_pk primary key (person_id) ); |
Sample data:
1 2 3 | PERSON_ID PERSON_NAME 1 Gary 2 Steve |
Update Cargo.toml With Crate That Can Connect To And Query Data from MySQL
Under the [dependencies] section, add the mysql = "16.1.0" :
1 2 3 4 5 6 7 8 9 10 | [package] name = "rust-project1" version = "0.1.0" authors = ["Karl San Gabriel"] edition = "2018" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] 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.
1 2 | extern crate mysql; ... |
Then, we need to create a struct that resembles and represents the persons table.
1 2 3 4 5 6 7 | ... #[derive(Debug, PartialEq, Eq)] struct Person { person_id: i32, person_name: String } ... |
In the main function, we first get a connection:
1 2 3 | ... let pool = mysql::Pool::new("mysql://root:a1128f69-e6f7-4e93-a2df-3d4db6030abc@localhost:3306/turretadb").unwrap(); ... |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | ... let all_persons: Vec<Person> = pool.prep_exec("SELECT person_id, person_name from person", ()) .map(|result| { result.map(|x| x.unwrap()).map(|row| { let (person_id, person_name) = mysql::from_row(row); Person { person_id, person_name } }).collect() }).unwrap(); // Unwrap `Vec<Person>` for person in all_persons.iter() { println!("{}: {}", person.person_id, person.person_name); } ... |
Finally, we test the application. When we run our application, we get the following output.
1 2 3 4 5 6 7 8 | C:/Users/karldev/.cargo/bin/cargo.exe run --color=always --package rust-project1 --bin rust-project1 Compiling rust-project1 v0.1.0 (C:\Users\karldev\Desktop\dev\blogs\rust\rust-project1) Finished dev [unoptimized + debuginfo] target(s) in 2.71s Running `target\debug\rust-project1.exe` 1: Gary 2: Steve Process finished with exit code 0 |
And that’s how we connect to MySQL from Rust and query for data! We tested the codes using Rust 1.37.0.
Thank you for sharing.
Under Rust Codes in your post you make reference to Postgres, is not supposed to be Mysql?
I’ve updated the post. It is supposed to be MySQL. Thank you for the hint.
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?
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?
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.