You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将MySQL查询结果列转换为String类型(Rust新手求助)

解决方案

1. 处理MySQL查询结果转String(含NULL转空串)

mysql::Value 未实现 Display trait,无法直接调用 to_string(),需要手动匹配其枚举变体完成转换:

use mysql::Value;

// 传递Row的引用避免不必要的所有权转移
fn as_string(row: &mysql::Row, index: usize) -> String {
    match row.as_ref(index) {
        // NULL值直接返回空字符串
        Some(Value::Null) => String::new(),
        // 整数类型转字符串
        Some(Value::Int(int_val)) => int_val.to_string(),
        Some(Value::UInt(uint_val)) => uint_val.to_string(),
        // 浮点数转字符串
        Some(Value::Float(float_val)) => float_val.to_string(),
        // 字符串类型直接克隆
        Some(Value::String(str_val)) => str_val.clone(),
        // 字节数组转UTF-8字符串(非UTF-8内容会被替换为�)
        Some(Value::Bytes(bytes_val)) => String::from_utf8_lossy(bytes_val).to_string(),
        // 日期、时间类型直接转字符串
        Some(Value::Date(date_val)) => date_val.to_string(),
        Some(Value::DateTime(dt_val)) => dt_val.to_string(),
        // 其他未覆盖的变体默认返回空串,可按需扩展处理逻辑
        _ => String::new(),
    }
}

2. 格式化time::PrimitiveDateTime去掉无用的.0毫秒

通过判断毫秒值是否为0,选择对应的格式化规则即可:

use time::PrimitiveDateTime;

fn format_datetime(dt: &PrimitiveDateTime) -> String {
    if dt.millisecond() == 0 {
        // 毫秒为0时,只显示到秒级
        dt.format("%Y-%m-%d %H:%M:%S").unwrap()
    } else {
        // 存在非0毫秒时,显示三位毫秒
        dt.format("%Y-%m-%d %H:%M:%S%.3f").unwrap()
    }
}

如果需要ISO8601格式,将格式化字符串替换为"%Y-%m-%dT%H:%M:%S"和"%Y-%m-%dT%H:%M:%S%.3f"即可。


内容的提问来源于stack exchange,提问作者Daniel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 08:10:19