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

如何将C#的BigInteger存储为MySQL DECIMAL(36,18)类型以存储Wei值

报错原因

你遇到的报错是因为MySQL官方.NET连接器原生不支持直接将BigInteger类型作为Decimal参数传入,直接赋值会抛出类型不支持异常。


解决方案(分两种场景)

场景1:按现有表结构存储Ether单位数值

你当前表的DECIMAL(36,18)结构刚好对应1 Ether = 1e18 Wei的换算规则,小数位可完全覆盖Wei换算后的精度,直接将BigInteger类型的Wei值换算为Ether单位的decimal类型即可:

public void AddTrade(BigInteger price) {
    // BigInteger转decimal,同时换算为Ether单位
    decimal etherPrice = (decimal)price / 1_000_000_000_000_000_000m;
    _connection.Open();
    var command = new MySqlCommand(@"INSERT INTO Prices (Price) VALUES (@Price);", _connection);
    command.Parameters.Add("@Price", MySqlDbType.Decimal).Value = etherPrice;
    command.ExecuteNonQuery();
    _connection.Close();
}

该方案适合绝大多数以太坊交易存储场景,只要数值不超过decimal的取值范围(±7.9e28)即可正常运行。


场景2:需要存储原始Wei整数值

如果你需要保留Wei的整数原值,建议先把表字段修改为DECIMAL(36,0),再将BigInteger转为字符串传入参数,MySQL会自动完成字符串到DECIMAL类型的转换,不需要额外处理:

修改后表结构代码

public void CreatePriceTable() {
    _connection.Open();
    var createTable = new MySqlCommand(
        @"
        CREATE TABLE `Prices` (
        Price DECIMAL(36,0) NOT NULL
        ) COLLATE='utf8_general_ci' ENGINE=InnoDB;"
        , _connection);
    createTable.ExecuteNonQuery();
    _connection.Close();
}

修改后插入代码

public void AddTrade(BigInteger price) {
    _connection.Open();
    var command = new MySqlCommand(@"INSERT INTO Prices (Price) VALUES (@Price);", _connection);
    // 直接转字符串传入,避免类型不支持和溢出问题
    command.Parameters.Add("@Price", MySqlDbType.Decimal).Value = price.ToString();
    command.ExecuteNonQuery();
    _connection.Close();
}

读取数据时,将查询到的decimal或字符串值转为BigInteger即可还原原始数值。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 15:15:00