You will need to get the Postgres driver first. In the terminal type:
go get github.com/lib/pq
Connecting to Postgres
package main import ( _ "github.com/lib/pq" "database/sql" "fmt" ) func main() { // Connect to the DB, panic if failed db, err := sql.Open("postgres", "postgres://user:password@localhost/dbName?sslmode=disable") if err != nil { fmt.Println(`Could not connect to db`) panic(err) } defer db.Close() }
Selecting data from a table
After connecting to the database, you can do the following:
rows, err := db.Query(`SELECT * FROM table WHERE name=$1`, `Moz`) if err != nil { panic(err) } var col1 string var col2 string for rows.Next() { rows.Scan(&col1, &col2) fmt.Println(col1, col2) }
Leave a Reply