Getting to Know Our Database
Let’s learn to connect to a database and query it for information.
We'll cover the following...
Working with a database
We most likely need to download an additional package for working with a database server such as PostgreSQL, MySQL, or MongoDB. In this case, we are using PostgreSQL and, therefore, need to download a Go package that allows us to communicate with PostgreSQL. There are two main Go packages for connecting to PostgreSQL—we are going to use the github.com/lib/pq
package here, but it is up to you to decide which package best suits the needs of your project.
Note: There is another Go package for working with PostgreSQL called
jackc/pgx
.
We can download the package of our choice as follows:
go get github.com/lib/pq
To make things simpler, the PostgreSQL server is executed from a Docker image using a docker-compose.yml
file, which has the following contents:
version: '3'services:postgres:image: postgrescontainer_name: postgresenvironment:- POSTGRES_USER=educative- POSTGRES_PASSWORD=pass- POSTGRES_DB=mastervolumes:- ./postgres:/var/lib/postgresql/data/networks:- psqlports:- "5432:5432"volumes:postgres:networks:psql:driver: bridge
The default port number the PostgreSQL server listens to is 5432
. Because we connect to that PostgreSQL server from the same machine, the hostname that is going to be used is localhost
or, if we prefer an IP address, 127.0.0.1
. If we are using a different PostgreSQL server, then, in the code that follows, we should change the connection details accordingly.
Note: In PostgreSQL, a schema is a namespace that contains named database ...