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.
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 github.com/lib/pq
Then, in your main.go
file, import the pq package along with database/sql
and fmt
:
import (
"database/sql"
"fmt"
_ "github.com/lib/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 {
panic(err)
}
defer db.Close()
And finally, we’ll open up a connection to the database using Ping()
:
err = db.Ping()
if err != nil {
panic(err)
}
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 {
panic(err)
}
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)
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