Skip to content

Instantly share code, notes, and snippets.

@itang
Created December 23, 2013 02:22
Show Gist options
  • Save itang/8090953 to your computer and use it in GitHub Desktop.
Save itang/8090953 to your computer and use it in GitHub Desktop.
golang + postgreSQL example
package main
import (
"database/sql"
"fmt"
"log"
// load postgres driver
_ "github.com/lib/pq"
)
func main() {
// Open db
db, err := sql.Open("postgres", "user=postgres password=postgres dbname=test sslmode=disable")
if err != nil {
log.Fatal(err)
}
defer db.Close()
rows, err := db.Query(
`SELECT amname, amstrategies, amsupport, amcanorder, amcanorderbyop,
amcanbackward, amcanunique, amcanmulticol, amoptionalkey, amsearcharray,
amsearchnulls, amstorage, amclusterable, ampredlocks, amkeytype,
aminsert, ambeginscan, amgettuple, amgetbitmap, amrescan, amendscan,
ammarkpos, amrestrpos, ambuild, ambuildempty, ambulkdelete, amvacuumcleanup,
amcanreturn, amcostestimate, amoptions
FROM pg_am`)
if err != nil {
log.Fatal(err)
}
// Columns
cs, err := rows.Columns()
if err != nil {
log.Fatal(err)
}
fmt.Printf("%v\n", cs)
// Query Row
var amname string
err1 := db.QueryRow(`SELECT amname FROM pg_am`).Scan(&amname)
switch {
case err1 == sql.ErrNoRows:
log.Printf("No user with that ID.")
case err1 != nil:
log.Fatal(err)
default:
fmt.Printf("amname is %s\n", amname)
}
// Query
rows1, err := db.Query(`SELECT amname FROM pg_am`)
if err != nil {
log.Fatal(err)
}
for rows1.Next() {
var amname string
if e := rows1.Scan(&amname); e != nil {
}
fmt.Printf("amname is %s\n", amname)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment