[database/sql] Scan rows to string arrays

11,302 views
Skip to first unread message

Frank Blechschmidt

unread,
Mar 11, 2013, 4:34:49 PM3/11/13
to golan...@googlegroups.com
Hey!

How to put SQL rows into an array of string arrays? (/convert SQL result to string matrix)

Thanks and best regards
Frank

Frank Blechschmidt

unread,
Mar 11, 2013, 5:08:15 PM3/11/13
to golan...@googlegroups.com
Found it.

Working solution:
var result [][]string
rows := repo.dbHandler.Query(sQuery)
cols := rows.Columns()
pointers := make([]interface{}, len(cols))
container := make([]string, len(cols))
for i, _ := range pointers {
pointers[i] = &container[i]
}
for rows.Next() {
rows.Scan(pointers...)
result = append(result, container)
}

Julien Schmidt

unread,
May 10, 2013, 10:34:48 PM5/10/13
to golan...@googlegroups.com, jksmi...@gmail.com
You are reusing the pointers so effectively you are overriding the content of the existing slices.
Something like this should work: http://play.golang.org/p/_mdS9X3USU

But I'd definitely recommend to use sql.RawBytes when ever possible.
Moreover you run into problems if a nil value occurs. In this case using a bytes slice or sql.NullString instead of string might be the better option.

On Friday, May 10, 2013 7:54:37 PM UTC+2, jksmi...@gmail.com wrote:
Hey Frank!

Slick way to cut the code when rawbytes won't work for the driver. 

This test however: PrintLn(result)
after the loop doesn't yield expected results. It just repeats the result set number of rows of the last row that was read. If I just PrintLn(container) in the loop, all the rows print. Maybe it's just a bug in PrintLn for arrays of strings.

Aras Can Akın

unread,
Mar 7, 2016, 2:46:16 PM3/7/16
to golang-nuts
I tried the []interface{} variant but it doesn't seem to be working. Can you help with this?

cols, _ := rows.Columns()
pointers := make([]interface{}, len(cols))
container := make([]interface{}, len(cols))


for i, _ := range pointers {
       pointers[i] = &container[i]
}

defer rows.Close()
for rows.Next() {
    fmt.Println(container)
}

it prints 
[<nil> [102 99 54 48 50 48 48 53 45 100 55 52 97 45 52 49 51 52 45 55 55 100 50 45 100 54 51 49 102 100 99 48 101 50 55 98] [114 111 98 101 114 116 64 100 101 45 110 105 114 111 46 99 111 109] [82 111 98 101 114 116 32 68 101 32 78 105 114 111] [114 100 110]]

where each value should be string or time.Time

dja...@gmail.com

unread,
Mar 7, 2016, 11:36:44 PM3/7/16
to golang-nuts
you miss scan:
`err = rows.Scan(pointers...)`

jnaradaj...@gmail.com

unread,
Sep 9, 2016, 8:18:44 AM9/9/16
to golang-nuts
TX!, This works for me
Reply all
Reply to author
Forward
0 new messages