reiner icon indicating copy to clipboard operation
reiner copied to clipboard

Bind 字段为NULL时出错

Open xiake999 opened this issue 7 years ago • 9 comments

@YamiOdymel 数据值为NULL时,Bind 出错:

Scan error on column index 5: unsupported Scan, storing driver.Value type <nil> into type *string

应该返回为空才对吧? 字段是默认值是NULL,不能因为这个问题程序出错?

xiake999 avatar Jul 06 '17 14:07 xiake999

Golang 預設不能存放 NULL 型態,如果你要對應 NULL 值,假設你有個 String 型態,你需要改用 sql.NullString(因為 Golang 的 String 零值是 "" 而不是 nil)。

YamiOdymel avatar Jul 06 '17 14:07 YamiOdymel

因為 Golang 裏針對資料庫的 NULL 處理起來會令人棘手,所以通常不建議設計有 NULL 的資料表。

NULL值处理 简单说就是设计数据库的时候不要出现null,处理起来非常费力。Null的type很有限,例如没有sql.NullUint64; null值没有默认零值。

https://segmentfault.com/a/1190000003036452#articleHeader17

YamiOdymel avatar Jul 06 '17 14:07 YamiOdymel

这我知道的.我记得xorm null 返回的是 "" ,而不是error。 sql.NullString 调用时需要进行转换吧

xiake999 avatar Jul 06 '17 14:07 xiake999

如果要將 NULL 自動轉換成型態的零值⋯⋯那可能就要改一下程式碼了,

我需要稍微看一下

YamiOdymel avatar Jul 06 '17 14:07 YamiOdymel

好的,非常感谢

xiake999 avatar Jul 06 '17 14:07 xiake999

研究了一下,這個錯誤來自 Reiner 底層的 SQL Driver(go-sql-driver)。

The error is returned by the database/sql package because of this goal:

  • Be flexible with type conversions, but be paranoid about silent truncation or other loss of precision.

You must use http://golang.org/pkg/database/sql/#NullString if the column may contain NULL values

https://github.com/go-sql-driver/mysql/issues/34

看起來現在底層的 Driver 有強制一項規則:如果欄位有機會是 NULL 值,就必須改用 NullString

感覺⋯⋯更棘手啦。

1499004760201

YamiOdymel avatar Jul 06 '17 14:07 YamiOdymel

辛苦了,我先使用sql.NullString解决当前问题,等空了我查阅资料找找解决办法

xiake999 avatar Jul 06 '17 15:07 xiake999

@YamiOdymel 你好,近期有计划优化性能吗?

xiake999 avatar Jul 24 '17 12:07 xiake999

@xiake999 抱歉,目前還沒有打算,可能會在九月之後再來研究

YamiOdymel avatar Jul 25 '17 06:07 YamiOdymel