When I tried to connect to a database for the first time I almost lost my mind. It was so frustrating and I do not want you to go through what I went through.
Backend applications and databases are a pair that cannot be separated. One of the major things we do as backend engineers is to connect to one or more databases. We insert and get information from the database.
There are so many databases out there but for this article, we will consider a relational, open-source database known as Postgres
Prerequisites
All you need is to have Go and Docker installed on your device. Insert smiley face.
Creating the project
The first step is to create the project folder and open it in your preferred text editor (I use VScode) what do you use?
You need to create the following files main.go and docker-compose.yml
touch main.go docker-compose.yml
Run the below code to track your packages
go mod int postgres
Install needed 3rd party packages
For this, you need only one package this an SQL driver
go get github.com/lib/pq
Fun Time
Why Docker? Docker is a powerful tool that allows developers to easily create, deploy, and manage applications in isolated containers.
One of the key advantages of using Docker is the ability to quickly spin up a Postgres service without the hassle of manually installing and configuring the database.
It's time for some real fun. Go to your docker file and write the following code block
services:
database:
image: postgres:12
environment:
POSTGRES_PASSWORD: postgres
POSTGRES_USER: postgres
POSTGRES_DB: postgres
ports:
- "5432:5432"
volumes:
- db:/var/lib/postgresql/data
volumes:
db:
Now you have defined a service in your docker-compose file. To use this you need to start that service up in docker with the command below
docker compose up db
In your main.go file you need some imports to begin connecting to your database
import (
"database/sql"
"fmt"
_"github.com/lib/pq"
)
A connection string points to your database. Please for the sake of simplicity, I am just placing the connection string right there in the code.
Please DO NOT do this in production as this can cause a huge security issue. You can use environmental variables to keep important information from being publicly accessed
connectionString := "host=localhost user=postgres password=postgres dbname=postgres sslmode=disable"
Your code should look like the one below
package main
import (
"database/sql"
"fmt"
_"github.com/lib/pq"
)
func main () {
connectionString := "host=localhost user=postgres password=postgres dbname=postgres sslmode=disable"
}
Connecting to your Postgres database can now be achieved with one line of code as seen below.
db, err := sql.Open("postgres", connectionString)
The beautiful thing about Golang and I love this about Golang is that it checks for errors when operations are carried out.
If for any reason we cannot connect to the database we get the beautiful error message.
if err != nil {
fmt.Println(err.Error)
}
defer db.Close()
Congratulations you have connected to your Postgres database but we need a way to test if the database connection was successful. You can ping your database.
if err := db.Ping(); err != nil {
fmt.Println(err.Error())
} else {
fmt.Println("Successfuly connected")
}
Unifying your code it should look like the below
package main
import (
"database/sql"
"fmt"
_"github.com/lib/pq"
)
func main () {
connectionString := "host=localhost user=postgres password=postgres dbname=postgres sslmode=disable"
db, err := sql.Open("postgres", connectionString)
if err != nil {
fmt.Println(err.Error())
}
defer db.Close()
// Test the connection to the database
if err := db.Ping(); err != nil {
fmt.Println(err.Error())
} else {
fmt.Println("Successfully Connected")
}
}
There you go easy, right? You can manage the database and perform CRUD operations on the database.