Skip to content

Instantly share code, notes, and snippets.

@tux21b
Created May 27, 2012 23:42
Show Gist options
  • Save tux21b/2816411 to your computer and use it in GitHub Desktop.
Save tux21b/2816411 to your computer and use it in GitHub Desktop.
package main
import (
"database/sql"
"fmt"
_ "github.com/bmizerany/pq"
"log"
)
func QueryMap(db *sql.DB, query string) (map[string]interface{}, error) {
rows, err := db.Query("select * from pg_tables")
if err != nil {
return nil, err
}
columns, err := rows.Columns()
if err != nil {
return nil, err
}
result := make(map[string]interface{})
if rows.Next() {
values := make([]interface{}, len(columns))
for i, _ := range columns {
values[i] = new(interface{})
}
err = rows.Scan(values...)
if err != nil {
return nil, err
}
for i, key := range columns {
result[key] = values[i]
}
}
return result, nil
}
func main() {
db, err := sql.Open("postgres", "user=christoph dbname=postgres sslmode=disable")
if err != nil {
log.Fatalf("sql.Open: %v", err)
}
result, err := QueryMap(db, "select * from pg_tables")
if err != nil {
log.Fatalf("QueryMap: %v", err)
}
fmt.Println(result)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment