on column index 0, name "sum": converting NULL to float64 is unsupported

2025年09月04日 13:47 响应: 13.17秒 状态: success

🚨 错误信息

/go/release/server/gin/controller/order/service.go:1818 sql: Scan error on column index 0, name "sum": converting NULL to float64 is unsupported

🤖 AI解决方案

/go/release/server/gin/controller/order/service.go:1818 sql: Scan error on column index 0, name "sum": converting NULL to float64 is unsupported
/go/release/server/gin/controller/order/service.go:1818 sql: Scan error on column index 0, name "sum": 将 NULL 转换为 float64 不受支持

原因分析

数据库查询结果中的 sum 字段为 NULL,而 Go 代码尝试将其直接赋值给 float64 类型的变量,Go 的 float64 类型不支持直接接收 NULL 值。

解决方案

修改代码,在扫描数据库结果时,将 float64 类型的字段改为使用 sql.NullFloat64 类型,并在后续处理中判断其 Valid 属性。

示例修改:

假设你原本的代码是这样的:

var sum float64
err := rows.Scan(&sum)

请修改为:

var sum sql.NullFloat64
err := rows.Scan(&sum)
if err != nil {
    // 处理扫描错误
}

var finalSum float64
if sum.Valid {
    finalSum = sum.Float64
} else {
    finalSum = 0.0 // 或者根据业务逻辑设置默认值
}

预防措施

  • 数据库设计:在数据库层面,为可能出现 NULL 值的数值型字段设置合理的默认值,或使用允许 NULL 的类型(如 sql.NullFloat64)。
  • 代码审查:在代码审查过程中,关注数据库查询结果的扫描逻辑,特别是对可能为 NULL 的字段的处理。