开发一套ERP 第七弹 RUst 操作数据库

发布于:2024-11-29 ⋅ 阅读:(30) ⋅ 点赞:(0)

感谢AI

use std::fmt::format;
use mysql::*;
use lazy_static::lazy_static;
use std::sync::Mutex;
use std::thread::sleep;
use std::time::Duration;
use log::log;
use mysql::prelude::Queryable;
use data::base::{ListData,SqlInstance};
use crate::data;

lazy_static! {
    pub static ref MYSQL_USER:Mutex<String> = Mutex::new(String::from("root"));
    pub static ref MYSQL_PASSWORD:Mutex<String> = Mutex::new(String::from("123456"));
    pub static ref MYSQL_POOL: Mutex<Pool> = Mutex::new(Pool::new
        (format!("mysql://{}:{}@localhost::3306/ERP",MYSQL_USER.lock().unwrap().as_str(),
            MYSQL_PASSWORD.lock().unwrap().as_str()).as_str())
        .expect("Connection to Mysql Error"));
}

//FIXME: 链接出错直接关闭回收链接错误
#[allow(non_snake_case)]
fn MysqlPoolConnect(max_retries:i32,delay:u64) -> Result<PooledConn> {
    let mut attempts = 0;
    let retry_delay = Duration::from_secs(delay);  // 设置重试的间隔时间
    loop {
        attempts += 1;
        let pool = MYSQL_POOL.lock()?;
        let conn_result = pool.get_conn();
        match conn_result {
            Ok(conn) => {
                return Ok(conn);
            }
            Err(err) => {
                if attempts >= max_retries {
                    return Err(err);
                }
                eprintln!("Failed to connect to database, attempt {} of {}: {}", attempts, max_retries, err);
                sleep(retry_delay);
            }
        }
    }
}

#[allow(non_snake_case)]
pub fn MysqlPoolSql(query:&mut SqlInstance){
   match MysqlPoolConnect(3,1) {
       Ok(mut pool) => {
           query.buffer = pool.query_map(query.filter.as_str(),|(id,name)| ListData { id,name, name_and_color: "".to_string(), avatar: "".to_string(), zh_size: "".to_string(), u_size: "".to_string(), factory_name: "".to_string(), output: 0, input: 0, diff: 0, threshold: 0, inputDate: "".to_string(), outputDate: "".to_string() }).unwrap();
       }
       Err(err) => {
            query.result = false;
            eprintln!("Failed to connect to database: {}", err);
       }
   }
}

Rust 的全局静态挺麻烦,语言默认是非安全的操作

Rust 有spdlog的 日志封装