Rust Web 全棧開發(五):使用 sqlx 連接 MySQL 數據庫
- Rust Web 全棧開發(五):使用 sqlx 連接 MySQL 數據庫
- 項目創建
- 數據庫準備
- 連接請求
- 功能實現
Rust Web 全棧開發(五):使用 sqlx 連接 MySQL 數據庫
本文是一個單獨的小項目。
參考文檔:https://blog.csdn.net/weixin_45987327/article/details/126117286
項目創建
新建一個 Rust 項目,打開 Cargo.toml,把 edition 改成 “2021”。
在 [dependencies] 部分添加:
actix-rt="2.7.0"
actix-web="4.1.0"
dotenv = "0.15.0"
chrono = {version = "0.4.19", features = ["serde"]}
serde = {version = "1.0.140", features = ["derive"]}
sqlx = {version = "0.6.0", default_features = false, features = ["mysql","runtime-tokio-rustls","macros","chrono",
]}
注意:在添加 crate 時,注意使用版本要相互兼容,否則會出現編譯警告。具體需要訪問 crates.io 來查看合適的版本。
在終端執行命令 cargo build,構建成功:
數據庫準備
新建一個名為 course 的 MySQL 數據庫,再新建一個名為 course 的表:
time 如果用 timestamp 類型的話,會報錯:error[E0277]: the trait bound `NaiveDate: From<DateTime>` is not satisfied,原因是:the trait `From<DateTime>` is not implemented for `NaiveDate`。
內容如下:
連接請求
在根項目的目錄下,新建名為 .env 的文件,在文件內寫入請求 URL,形如:
DATABASE_URL=mysql://{user}:{password}@{IP}:{port}/{database name}
這里,我的請求 URL 是:
DATABASE_URL=mysql://root:12138@127.0.0.1:3306/course
功能實現
參考文檔:https://docs.rs/sqlx/0.6.0/sqlx/mysql/index.html
use chrono::NaiveDateTime;
use dotenv::dotenv;
use sqlx::mysql::MySqlPoolOptions;
use std::env;
use std::io;#[derive(Debug)]
pub struct Course {pub id: i32,pub teacher_id: i32,pub name: String,pub time: Option<NaiveDateTime>,
}#[actix_rt::main]
async fn main() -> io::Result<()> {// 檢測并讀取 .env 文件中的內容,若不存在也會跳過異常dotenv().ok();let database_url = env::var("DATABASE_URL").expect("DATABASE_URL 沒有在 .env 文件里設置");let db_pool = MySqlPoolOptions::new().connect(&database_url).await.unwrap();let course_rows = sqlx::query!(r#"SELECT id, teacher_id, name, time FROM course"#).fetch_all(&db_pool).await.unwrap();let mut courses_list = vec![];for row in course_rows {courses_list.push(Course {id: row.id,teacher_id: row.teacher_id,name: row.name,time: Some(chrono::NaiveDateTime::from(row.time.unwrap())),})}println!("Courses = {:?}", courses_list);Ok(())
}
運行結果: