Questions And Answers

More Tutorials

RUST Connect And Run Query against MySQL

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

extern crate mysql;

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

#[derive(Debug, PartialEq, Eq)]
struct Person {
    person_id: i32,
    person_name: String

In the main function, we first get a connection:

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.

let all_persons: Vec<Person> =
        pool.prep_exec("SELECT person_id, person_name from person", ())
            .map(|result| {
      |x| x.unwrap()).map(|row| {
                    let (person_id, person_name) = mysql::from_row(row);
                    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.

C:/Users/user/.cargo/bin/cargo.exe run --color=always --package rust-project1 --bin rust-project1
   Compiling rust-project1 v0.1.0 (C:\Users\user\Desktop\dev\rust-MYSQL-Example)
    Finished dev [unoptimized + debuginfo] target(s) in 2.71s
     Running `target\debug\rust-project1.exe`
1: Jhon
2: William


In this page (written and validated by ) you learned about Rust MYSQL Select . What's Next? If you are interested in completing Rust tutorial, we encourage you simply to start here: Rust Tutorial.

Incorrect info or code snippet? We take very seriously the accuracy of the information provided on our website. We also make sure to test all snippets and examples provided for each section. If you find any incorrect information, please send us an email about the issue:

Share On:

Mockstacks was launched to help beginners learn programming languages; the site is optimized with no Ads as, Ads might slow down the performance. We also don't track any personal information; we also don't collect any kind of data unless the user provided us a corrected information. Almost all examples have been tested. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. By using, you agree to have read and accepted our terms of use, cookies and privacy policy.