Instagram
youtube
Facebook
Twitter

How to Connect Postgres SQL with Golang

PostgreSql

Here we have a tendency to ar aiming to explore victimization PostgreSQL with Go. we have a tendency to ar aiming to begin out pretty straightforwardly and can solely be connecting to the information here, however, if you're acquainted with SQL you'll discover that when you get connected to your information you'll terribly quickly begin utilizing it together with your existing SQL information.

Get the go package 

Here, pet dog packages are very cute and artificial and lib/pg is the best driver for PostgreSql. here is the command needed to get the package:

go get -u github.com/lib/pq

 PostgreSQL database

We must first ensure that we have the correct information before connecting to our database. If this information is incorrect, no matter what you try in your code, you will be unable to interact with your database without the proper credentials!

Unfortunately, your credentials and the other database information you'll need aren't set in stone. You probably chose the name of the database, the user (aka role) that will be used to login to Postgres, and a custom password for that user.

const (
  host     = "localhost"
  port     = 5432
  user     = "postgres"
  password = "your-password"
  dbname   = "sample database"
)

The majority of these should look familiar. If you're connecting to a Postgres database running on the same computer you're developing on, the host will almost certainly be a local host and the port will almost certainly be 5432. If that is not the case, I will assume you have a way to find that information.

Connecting string

here we are creating connection string tiles that contains all the necessary information in order to connect to the postgre database.

func main() {

  informationForPostgreSql := fmt.Sprintf("host=%s port=%d user=%s "+

    "password=%s dbname=%s sslmode=disable",

    host, port, user, password, dbname)

}

here we have added all the required parameters in order to connect out Postgres database.

 

Connecting to the server

package main

import (

  "database/sql"
  "fmt"

  "github.com/lib/pq"

)

const (

  host     = "localhost"
  port     = 5432
  user     = "postgres"
  password = "your-password"
  dbname   = "test_database"

)

func main() {

  informationForPostgreSql := fmt.Sprintf("host=%s port=%d user=%s "+
    "password=%s dbname=%s sslmode=disable",
    host, port, user, password, dbname)
  db, err := sql.Open("postgres", informationForPostgreSql) // checking the connection and connecting
  
  if err != nil {
    panic(err)
  }

  defer db.Close()

  err = db.Ping()

  if err != nil { //error handling 
    panic(err)
  }

  fmt.Println("connected!")
}

Outputs:

connected