How to handle null values in gorp Select

huangapple go评论76阅读模式
英文:

How to handle null values in gorp Select

问题

我正在尝试按照以下方式从数据库中获取用户:

var users []User
_, err := dbMap.Select(&users, "select id,username,acctstarttime,acctlastupdatedtime,acctstoptime from accounting order by id")

在这里,我使用了 gorp。当存在空值时,会抛出异常:

Select failed sql: Scan error on column index 3: unsupported driver -> Scan pair: <nil> -> *string

如何解决这个问题?我使用 gorp 是因为它可以方便地将输出映射到一个结构体数组中。

英文:

I'm trying to get the users from a DB as follow,

var users []User
_, err := dbMap.Select(&amp;users, &quot;select id,username,acctstarttime,acctlastupdatedtime,acctstoptime from accounting order by id&quot;)

Here I'm using gorp. When there are null values present, this throws exception

 Select failed sql: Scan error on column index 3: unsupported driver -&gt; Scan pair: &lt;nil&gt; -&gt; *string 

How can I solve this issue?. Here I used gorp because of the ease of mapping the output to a struct array.

答案1

得分: 2

将acctstarttime映射为指向该类型的指针,而不是该类型的值。

如果列为空,指针将为nil。

或者你可以使用sql.NullXXX类型,但我通常不喜欢使用它们,因为它们会使其他事情变得奇怪。

英文:

Make whatever acctstarttime maps to a pointer to the type instead of a value of the type.

if the col is null, the pointer will be nil.

that or you can use the sql.NullXXX types, but I usually don't like those since they make everything else weird.

huangapple
  • 本文由 发表于 2015年9月26日 17:01:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/32795407.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定