Skip to content
This repository has been archived by the owner on Jan 4, 2022. It is now read-only.

Bind 字段为NULL时出错 #4

Open
xiake999 opened this issue Jul 6, 2017 · 9 comments
Open

Bind 字段为NULL时出错 #4

xiake999 opened this issue Jul 6, 2017 · 9 comments
Assignees

Comments

@xiake999
Copy link

xiake999 commented Jul 6, 2017

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

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

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

@YamiOdymel
Copy link
Member

YamiOdymel commented Jul 6, 2017

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

@YamiOdymel
Copy link
Member

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

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

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

@xiake999
Copy link
Author

xiake999 commented Jul 6, 2017

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

@YamiOdymel
Copy link
Member

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

我需要稍微看一下

@YamiOdymel YamiOdymel self-assigned this Jul 6, 2017
@xiake999
Copy link
Author

xiake999 commented Jul 6, 2017

好的,非常感谢

@YamiOdymel
Copy link
Member

研究了一下,這個錯誤來自 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

go-sql-driver/mysql#34

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

感覺⋯⋯更棘手啦。

1499004760201

@xiake999
Copy link
Author

xiake999 commented Jul 6, 2017

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

@xiake999
Copy link
Author

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

@YamiOdymel
Copy link
Member

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

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants