Use the sqlx crate with the mysql feature to connect to MySQL from Rust.
- Add the dependency to your
Cargo.tomlfile.
[dependencies]
sqlx = { version = "0.7", features = ["mysql"] }
- 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(())
}