Created
May 27, 2012 23:42
-
-
Save tux21b/2816411 to your computer and use it in GitHub Desktop.
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/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