App overview screenshotSQL and Database Guides
Try our free SQL Client
Connecting to Postgres
Connecting to Drivers
Installing Postgres
Setting up Postgres
Postgres   >   
Connecting to Drivers   >   
Postgres with Go

Learn How to Connect PostgreSQL with Go

If you’re working on a project in Go, you often need a database to store information. PostgreSQL is one of the most popular database systems available today. In this guide, we’ll walk you through how to connect your Postgres database with Go.

What You’ll Need

Installing pq

In order for Go projects to interact with a PostgreSQL database, you’ll need to install and import a PostgreSQL adapter. There are multiple options, but the most widely used Postgres driver for Go is currently pq. Navigate to your project directory and then add pq to your Go modules:

go get

Then, in your main.go file, import the pq package along with database/sql and fmt:

import (
  _ ""

Connecting to Your PostgreSQL Database Using pq

You’ll need to have your Postgres credentials. You can use this guide to find your credentials.

Once you have your credentials, declare the following constants for your connection credentials, and build a connection string:

const (
  host     = "localhost"
  port     = 5432
  user     = "myUser"
  password = "myPassword"
  dbname   = "myDB"

connString := fmt.Sprintf(“host=%s port=%s user=%s “ + 
   “password=%s dbname = %s sslmode=disable”, 
   host, port, user, password, dbname)

We can then use sql.Open() to validate our connection string and create an sql.DB object:

db, err := sql.Open(“postgres”, connString)
if err != nil {
defer db.Close()

And finally, we’ll open up a connection to the database using Ping():

err = db.Ping()
if err != nil {

Querying Your Database

Once you have established your connection, you can query your Postgres database from Go. To create and run a query, use Query() for SELECT statements like this:

myResult, err := db.Query(“SELECT ‘Arctype Archive: Your #1 Database Resource’ as message”)
if err != nil {
defer myResult.Close()

You can also pass variables to Query() for both text and values parameters like this:

text := “SELECT * FROM Users WHERE username = ?” 
values := “arctype”
myResult, err := db.Query(text, values)

Using an SQL Client with Postgres and Go

Now that you’ve connected Postgres to your Go project, you often need to add or edit data. We recommend using an SQL client to do so. Check out our guide for setting up Postgres with Arctype in this tutorial

Get help on databases and SQL. Join our Discord community.