panic: sql: expected 1 destination arguments in Scan, not <number> golang, pq, sql
19,243
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)
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
}
Comments
-
Chandu almost 2 years
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: expected 1 destination arguments in Scan, not 3. As per row.Scan can pass n number of destination arguments. Whats wrong with this code?
-
Chandu over 8 yearsYes, Its working @MuffinTop. I have lot of data->> fields in my table. Can you please share a piece of code how to use "data as a single field and decode the result with the encoding/json package."
-
Chandu over 8 yearsThanks a lot @MuffinTop :)
-
Chandu over 8 yearsJust to notify you json.Unmarshal instead of json.Decode. Code working as a charm. thanks again
-
Rahul Satal over 4 yearsThe solution really looks good. But I am not able to implement it. I am still getting the same error. You can see my code here - play.golang.org/p/x_P50Ode4QU. Do you have any idea what mistake I am doing?
-
Cerise Limón over 4 years@RahulSatal The details of this answer are only relevant to your application if you are using a Postgres JSONB field. Fix your application by passing the address of the individual fields to Scan.
-
Rahul Satal over 4 years@CeriseLimón Yes, I am using SQL Server and this fix is not working for it. Thanks for your response.