Skip to main content

Command Palette

Search for a command to run...

Postgres Database Connection using Golang

Updated
•1 min read•View as Markdown
Postgres Database Connection using Golang

In this article, we will explore how to connect the PostgresSQL database with Go using Go's database package

Prerequisites

  • Install Golang

  • Instal Postgres and PGAdmin or Run this Docker image

  • Basic understanding of SQL

Create a main.go file, run go mod init <module Name>, and Install the Go Database package

go mod init <moduleName>
go get github.com/go-pg/pg

In main.go file we will import the package, create a user Struct, initialize the Database connection and Create a Table by passing the model interface

package main

import (
    "github.com/go-pg/pg"
    "github.com/go-pg/pg/orm"
)

type User struct {
    Name   string
    Emails string
}

func StartConnection() {
    db := pg.Connect(&pg.Options{
        Addr:     ":5432",
        User:     "username",
        Password: "password",
        Database: "database-name",
    })

    err := createSchema(db)
    if err != nil {
        panic(err)
    }

}

// createSchema creates database schema for User models.
func createSchema(db *pg.DB) error {
    models := []interface{}{
        (*User)(nil),
    }

    for _, model := range models {
        err := db.Model(model).CreateTable(&orm.CreateTableOptions{
            Temp:        false,
            IfNotExists: true,
        })
        if err != nil {
            return err
        }
    }
    return nil
}