Skip to content

Instantly share code, notes, and snippets.

@moroz
Last active December 18, 2023 13:58
Show Gist options
  • Save moroz/77803235de65b785794ab85966e54a09 to your computer and use it in GitHub Desktop.
Save moroz/77803235de65b785794ab85966e54a09 to your computer and use it in GitHub Desktop.
Introduction to databases in Go

Homework for 12/17

Write a program that connects to a Postgres database and stores contact information in a table.

Sample input:

$ go run .
First name: John
Last name: Smith
Phone no: +1555123456
Email: john.smith@example.com
Date of birth: 1998-05-01
SAVED!

Remember to use correct data types. Refer to Postgres documentation for CREATE TABLE, INSERT INTO.

Subtask 1

Write a program that prompts the user for the relevant data using fmt.Scanf or fmt.Scanln.

Subtask 2

Convert the date of birth to a Go data structure using time.Parse.

Subtask 3

Write a program that connects to a PostgreSQL database using database/sql or sqlx.

Use URL format for the connection string:
https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-CONNSTRING

Execute a simple SQL query (e. g. select 2 + 2 or select now()) and print its output to STDOUT to ensure that the connection works.

Subtask 4

Write a function that creates a table if it does not exist. This table must have a primary key (a bigint incrementing automatically).

You can use create table if not exists ....

For ID, use ... generated by default by identity.

Subtask 5

Write the data to the database table using database/sql or sqlx. Consult the docs for insert into ....

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment