db

Postgres With Go

Two things are required to interact with the database: A library A driver Our library to interact with the database is ““database/sql” which is from the standard library. While the driver is “github.com/jackc/pgx/v4” which provides also a toolkit or library to interact with the database, but in this case we will it only for getting the driver. The below code is just one example: package main import ( "database/sql" "fmt" _ "github.

Interacting With the Database

Today it was a bit of lazy day so here it is… docker compose start [+] Running 2/2 ⠿ Container section-9-adminer-1 Started 0.4s ⠿ Container section-9-db-1 Started docker compose exec -it db psql -U baloo -d lenslocked psql (15.2 (Debian 15.2-1.pgdg110+1)) Type "help" for help. lenslocked=# lenslocked=# Deleting (dropping) a table lenslocked=# DROP TABLE IF EXISTS users; DROP TABLE lenslocked=# Adding comments lenslocked'# lenslocked'# -- Creating the "users" table lenslocked'# Creating a table lenslocked=# CREATE TABLE users ( lenslocked(# id SERIAL PRIMARY KEY, lenslocked(# age INT, lenslocked(# first_name TEXT, lenslocked(# last_name TEXT, lenslocked(# email TEXT UNIQUE NOT NULL lenslocked(# ); CREATE TABLE lenslocked=# lenslocked=# SELECT * FROM users; id | age | first_name | last_name | email ----+-----+------------+-----------+------- (0 rows) lenslocked=# lenslocked=# INSERT INTO users VALUES (1, 22, 'Alex', 'Rabocse', 'alex@email.

Connecting to Postgres

First, I am running postgres in a container. More specifically, I am using docker compose, so here is the yaml file: version: "3.9" services: # Our Postgres database db: # The service will be named db. image: postgres # The postgres image will be used restart: always # Always try to restart if this stops running environment: # Provide environment variables POSTGRES_USER: baloo # POSTGRES_USER env var w/ value baloo POSTGRES_PASSWORD: junglebook POSTGRES_DB: lenslocked # Database name ports: # Expose ports so that apps not running via docker-compose can connect to them.