toml
[dependencies]
mysql = "25.0.0"
[[bin]]
name = "mysql"
path = "src/mysql.rs"
mysql.rs
use mysql::*;
use mysql::prelude::*;
fn main() {
let url = "mysql://root:root@localhost:3306/fiber";
let pool = Pool::new(url).unwrap();
let id = insert_data(&pool, "Test Data", 100);
println!("ID: {}", id);
let del = delete_data(&pool, 1);
println!("del: {}", del);
let upes = update_data(&pool, id as i32, "Updated Test Data", 200);
println!("upes: {}", upes);
let results = query_data(&pool);
for row in results {
let id: i32 = row.0; // 获取列 id 的值
let test: String = row.1; // 获取列 test 的值
let num: i32 = row.2; // 获取列 num 的值
println!("ID: {}, Test: {}, Num: {}", id, test, num);
}
}
pub fn insert_data(pool: &Pool, test: &str, num: i32) -> u64 {
let mut conn = pool.get_conn().unwrap();
let stmt = conn.prep("INSERT INTO fiber_user (test, num) VALUES (?,?)").unwrap();
conn.exec_drop(&stmt, (test, num)).unwrap();
return conn.last_insert_id();
}
pub fn delete_data(pool: &Pool, id: i32) -> u64 {
let mut conn = pool.get_conn().unwrap();
let stmt = conn.prep("DELETE FROM fiber_user WHERE id = ?").unwrap();
conn.exec_drop(&stmt, (id,)).unwrap();
return conn.affected_rows();
}
pub fn update_data(pool: &Pool, id: i32, test: &str, num: i32) -> u64 {
let mut conn = pool.get_conn().unwrap();
let stmt = conn.prep("UPDATE fiber_user SET test = ?, num = ? WHERE id = ?").unwrap();
conn.exec_drop(&stmt, (test, num, id)).unwrap();
return conn.affected_rows();
}
pub fn query_data(pool: &Pool) -> Vec<(i32, String, i32)> {
let mut conn = pool.get_conn().unwrap();
let results: Vec<(i32, String, i32)> = conn.query("SELECT id, test, num FROM fiber_user").unwrap();
return results;
}
执行
cargo run --bin mysql
标签:unwrap,pool,改查,num,let,rust,mysql,id,conn
From: https://www.cnblogs.com/qcy-blog/p/18475689