go data_error ai_generated true

SQL 扫描错误:列索引 3 上无法将 NULL 转换为字符串

sql: Scan error on column index 3: converting NULL to string is unsupported

ID: go/database-scan-null-field

其他格式: JSON · Markdown 中文 · English
90%修复率
88%置信度
1证据数
2023-03-10首次发现

版本兼容性

版本状态引入弃用备注
Go 1.18 active
Go 1.19 active
Go 1.20 active
Go 1.21 active
Go 1.22 active

根因分析

将数据库中的 NULL 值扫描到非指针的 Go 类型(例如,使用 string 而不是 *string 或 sql.NullString)。

English

Scanning a NULL database value into a non-pointer Go type (e.g., string instead of *string or sql.NullString).

generic

官方文档

https://pkg.go.dev/database/sql#NullString

解决方案

  1. 对可空列使用 sql.NullString 或 *string,并在使用前检查 .Valid
  2. 将自定义结构体字段定义为指针以处理 NULL

无效尝试

常见但无效的做法:

  1. 60% 失败

    This masks the data issue and can lead to incorrect business logic if NULL has semantic meaning.

  2. 80% 失败

    Pollutes the data and may break other queries or reports.