恐慌:sql:在扫描中预期 1 个目标参数,而不是 golang、pq、sql

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

panic: sql: expected 1 destination arguments in Scan, not <number> golang, pq, sql

问题

我正在使用db.QueryRow获取数据。使用PostgreSQL创建了一个带有jsonb数据类型的表。以下是在Golang中的代码示例:

m := Message{}
err := db.QueryRow("SELECT data FROM message WHERE data->>'id'=$1", id).Scan(&m.Id, &m.Type, &m.Title)

出现错误:panic: sql: expected 1 destination arguments in Scan, not 3。根据row.Scan的说明,可以传递任意数量的目标参数。这段代码有什么问题?

英文:

I am fetching the data using db.QueryRow. Table created using Postgresql with data type jsonb. Below is code in golang

m := Message{}
err := db.QueryRow(&quot;SELECT data FROM message WHERE data-&gt;&gt;&#39;id&#39;=$1&quot;, id).Scan(m.Id, m.Type, m.Title)

panic: sql: expected 1 destination arguments in Scan, not 3. As per row.Scan can pass n number of destination arguments. Whats wrong with this code?

答案1

得分: 18

查询每行返回一个字段。代码正在扫描三个字段。也许你想要像这样的结果:

err := db.QueryRow("SELECT data->>'id', data->>'type', data->>'title' FROM message WHERE data->>'id'=$1", id).Scan(&m.Id, &m.Type, &m.Title)

另外,将值传递给指针:

err := db.QueryRow("SELECT data->>'id', data->>'type', data->>'title' FROM message WHERE data->>'id'=$1", id).Scan(&m.Id, &m.Type, &m.Title)

另一种选择是将数据作为单个字段获取,并使用encoding/json包解码结果。

var p []byte
err := db.QueryRow("SELECT data FROM message WHERE data->>'id'=$1", id).Scan(&p)
if err != nil {
    // 处理错误
}
var m Message
err := json.Unmarshal(p, &m)
if err != nil {
    // 处理错误
}
英文:

The query returns one field per row. The code is scanning for three. Perhaps you want something like:

err := db.QueryRow(&quot;SELECT data-&gt;&gt;&#39;id&#39;, data-&gt;&gt;&#39;type&#39;, data-&gt;&gt;&#39;title&#39; FROM message WHERE data-&gt;&gt;&#39;id&#39;=$1&quot;, id).Scan(m.Id, m.Type, m.Title)

Also, pass pointers to the values:

err := db.QueryRow(&quot;SELECT data-&gt;&gt;&#39;id&#39;, data-&gt;&gt;&#39;type&#39;, data-&gt;&gt;&#39;title&#39; FROM message WHERE data-&gt;&gt;&#39;id&#39;=$1&quot;, id).Scan(&amp;m.Id, &amp;m.Type, &amp;m.Title)

Another option is to fetch the data as a single field and decode the result with the encoding/json package.

var p []byte
err := db.QueryRow(&quot;SELECT data FROM message WHERE data-&gt;&gt;&#39;id&#39;=$1&quot;, id).Scan(&amp;p)
if err != nil {
    // handle error
}
var m Message
err := json.Unmarshal(p, &amp;m)
if err != nil {
    // handle error
}

huangapple
  • 本文由 发表于 2016年2月1日 02:36:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/35117714.html
匿名

发表评论

匿名网友

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

确定