Golang: Connect to Postgres and selecting data from a table

You will need to get the Postgres driver first. In the terminal type:

go get

Connecting to Postgres

package main

import (
    _ ""

func main() {
    // Connect to the DB, panic if failed
    db, err := sql.Open("postgres", "postgres://user:[email protected]/dbName?sslmode=disable")
    if err != nil {
        fmt.Println(`Could not connect to db`)
    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 {

var col1 string
var col2 string
for rows.Next() {
    rows.Scan(&col1, &col2)
    fmt.Println(col1, col2)

By Moazzam

Moazzam is a software developer working in the big apple. He has over a decade of experience in development. While most of his work involves developing web applications, he does development for Android and Windows Mobile in his spare time.

Leave a Reply

Your email address will not be published. Required fields are marked *