rust操作mysql增删改查

toml

[dependencies]
mysql = "25.0.0"
[[bin]]
name = "mysql"
path = "src/mysql.rs"

mysql.rs

use mysql::*;
use mysql::prelude::*;

#[derive(Debug)]
struct User {
    id: u64,
    test: String,
    num: u64
}

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);
            }
    let res2 =  query_dat2(&pool);    
    for row in res2 {
        println!("ID: {}, Test: {}, Num: {}", row.id, row.test, row.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;
}
pub fn query_dat2(pool: &Pool) -> Vec<User> {
    let mut conn = pool.get_conn().unwrap();
    // 执行查询并映射结果到 User 结构体
    let results =  conn.query_map("SELECT id, test, num FROM fiber_user", 
        | (id, test, num)| {User {id, test,num}},).unwrap();
    return results;
}

执行

cargo run --bin mysql
posted @ 2024-10-19 11:34  朝阳1  阅读(51)  评论(0编辑  收藏  举报