Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

postgresql

go

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?

like image 884
Chandu Avatar asked Jan 31 '16 18:01

Chandu


1 Answers

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
}
like image 146
Bayta Darell Avatar answered Oct 04 '22 13:10

Bayta Darell