Last active
December 31, 2015 15:39
-
-
Save lc0/8008534 to your computer and use it in GitHub Desktop.
friendly querying of data in Go
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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))) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
another solution is to use reflection and https://github.com/jmoiron/sqlx/blob/master/sqlx.go#L522