问题描述
我正在使用db.QueryRow获取数据.使用Postgresql创建的数据类型为jsonb的表.下面是golang中的代码
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("SELECT data FROM message WHERE data->>'id'=$1", id).Scan(m.Id, m.Type, m.Title)
panic:sql:在Scan中应该有1个目标参数,而不是3.按照行.Scan 可以传递n个目标参数.该代码有什么问题?
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?
推荐答案
查询每行返回一个字段.该代码正在扫描三个.也许您想要类似的东西:
The query returns one field per row. The code is scanning for three. Perhaps you want something like:
err := db.QueryRow("SELECT data->>'id', data->>'type', data->>'title' FROM message WHERE data->>'id'=$1", id).Scan(m.Id, m.Type, m.Title)
此外,将指针传递给值:
Also, pass pointers to the values:
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包对结果进行解码.
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("SELECT data FROM message WHERE data->>'id'=$1", id).Scan(&p)
if err != nil {
// handle error
}
var m Message
err := json.Unmarshal(p, &m)
if err != nil {
// handle error
}
这篇关于panic:sql:预期在Scan中有1个目标参数,而不是< number>golang,pq,sql的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!