Skip to content

Instantly share code, notes, and snippets.

@lc0
Last active December 31, 2015 15:39
Show Gist options
  • Save lc0/8008534 to your computer and use it in GitHub Desktop.
Save lc0/8008534 to your computer and use it in GitHub Desktop.
friendly querying of data in Go
package main
import (
"database/sql"
"fmt"
_ "github.com/go-sql-driver/mysql"
)
func main() {
db, err := sql.Open("mysql", "user:pass@tcp(127.0.0.1:3306)/database")
if err != nil {
panic(err.Error())
}
defer db.Close()
rows, err := db.Query("SELECT a_id, a_ip, a_type, a_float FROM t_table")
if err != nil {
panic(err.Error())
}
for rows.Next() {
cols, err := rows.Columns()
if err != nil {
fmt.Println("Failed to get columns", err)
return
}
rawResult := make([][]byte, len(cols))
dest := make([]interface{}, len(cols)) // A temporary interface{} slice
for i, _ := range rawResult {
dest[i] = &rawResult[i] // Put pointers to each string in the interface slice
}
err2 := rows.Scan(dest...)
if err2 != nil {
fmt.Println(err)
}
fmt.Println(string(*dest[1].(*[]uint8)))
}
}
@lc0
Copy link
Author

lc0 commented Dec 18, 2013

another solution is to use reflection and https://github.com/jmoiron/sqlx/blob/master/sqlx.go#L522

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment