How to Connect to MySQL from Rust

Connect to MySQL from Rust by adding the sqlx crate with the mysql feature and initializing a connection pool.

Use the sqlx crate with the mysql feature to connect to MySQL from Rust.

  1. Add the dependency to your Cargo.toml file.
[dependencies]
sqlx = { version = "0.7", features = ["mysql"] }
  1. Create a connection pool and execute a query in your Rust code.
use sqlx::MySql;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let pool = sqlx::MySqlPool::connect("mysql://user:pass@localhost/dbname").await?;
    let row = sqlx::query("SELECT 1 + 1 AS sum").fetch_one(&pool).await?;
    let sum: i32 = row.get("sum");
    println!("Sum: {}", sum);
    Ok(())
}