Connecting the database
The essential part of working with the database is the connection to the database itself. The Go standard package covers only the abstraction on how the interaction with the database works, and a third-party driver must be used.
In this recipe, we will show how to connect to the PostgreSQL database. However, the approach is applicable to all other databases whose driver implements the standard API.
Getting ready
Verify if Go is properly installed by calling the go version
command in your Terminal. If the command fails, do the following:
- Pull the PostgreSQL driver by
go get -u github.com/lib/pq
- Install the PostgreSQL database server (optionally use a Docker image instead of installing to your host system)
- We will use default user
postgres
with passwordpostgres
- Create a database named
example
How to do it...
- Open the console and create the folder
chapter08/recipe01
. - Navigate to the directory.
- Create the
connect.go
file with the following content:
package main import...