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

感谢AI

rust 复制代码
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的 日志封装

相关推荐
爬山算法1 小时前
Redis(158)Redis的主从同步问题如何解决?
数据库·redis·缓存
hjlgs4 小时前
framework修改快速验证
android
2501_941148154 小时前
多语言微服务架构与边缘计算技术实践:Python、Java、C++、Go深度解析
数据库
游戏开发爱好者85 小时前
iOS 开发者的安全加固工具,从源码到成品 IPA 的多层防护体系实践
android·安全·ios·小程序·uni-app·cocoa·iphone
四问四不知5 小时前
Rust语言进阶(结构体)
开发语言·后端·rust
w***z505 小时前
MYSQL 创建索引
数据库·mysql
安卓理事人5 小时前
安卓内存泄露排查LeakCanary
android
章鱼哥7306 小时前
[特殊字符] SpringBoot 自定义系统健康检测:数据库、Redis、表统计、更新时长、系统性能全链路监控
java·数据库·redis
5***E6856 小时前
MySQL:drop、delete与truncate区别
数据库·mysql
记得记得就1516 小时前
【MySQL数据库管理】
数据库·mysql·oracle