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

Rust中使用sqlx匹配MySQL Decimal类型的问题排查

解决sqlx查询MySQL Decimal类型时的Decode trait未实现问题

问题核心是你的Cargo.toml依赖配置存在冗余、版本不一致问题,且未给sqlx启用对应Decimal类型的支持feature,导致sqlx无法将MySQL的decimal列解码为Rust中的Decimal类型。

步骤1:清理并修正Cargo.toml依赖

先移除冗余的sqlx-core、sqlx-mysql、mysql依赖(sqlx本身已包含MySQL驱动功能),然后给sqlx添加对应Decimal类型的feature,同时确保所有依赖版本匹配:

方案A:使用rust_decimal(推荐)

[dependencies]
sqlx = { version = "0.7", features = [ "runtime-tokio", "mysql", "chrono", "rust_decimal" ] }
tokio = { version = "1.32.0", features = ["full"] }
chrono = { version = "0.4.10", features = ["serde"] }
rust_decimal = { version = "1.31.0", features = ["serde"] }
futures-util = "0.3.1"

方案B:使用bigdecimal

[dependencies]
sqlx = { version = "0.7", features = [ "runtime-tokio", "mysql", "chrono", "bigdecimal" ] }
tokio = { version = "1.32.0", features = ["full"] }
chrono = { version = "0.4.10", features = ["serde"] }
bigdecimal = { version = "0.4.1", features = ["serde"] }
futures-util = "0.3.1"

步骤2:在代码中使用正确的类型并导入

根据你选择的方案,在代码顶部导入对应的Decimal类型:

方案A(rust_decimal)代码示例

use rust_decimal::Decimal;

// ... 其他初始化代码(比如连接池) ...

// 注意:直接用静态字符串,避免format!拼接SQL防止注入
let query = "select price from My_Table";
let query_result = sqlx::query(query)
    .fetch_all(&pool)
    .await
    .expect("Failed to execute query");

for row in query_result {
    let price: Decimal = row.get("price");
    // 这里可以处理price值
}

方案B(bigdecimal)代码示例

use bigdecimal::BigDecimal;

// ... 其他初始化代码 ...

let query = "select price from My_Table";
let query_result = sqlx::query(query)
    .fetch_all(&pool)
    .await
    .expect("Failed to execute query");

for row in query_result {
    let price: BigDecimal = row.get("price");
    // 处理price值
}

额外提示

不要用format!拼接SQL语句,这会带来SQL注入风险。如果需要动态参数,使用sqlx的参数化查询,比如sqlx::query("select price from My_Table where id = ?")并绑定参数。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 02:33:22