programming

03 Creating a Database on MySQL Golang

At this stage we will try to create a database on MySQL in preparation for creating the table that we will also use later to create an API with the data in the database. Previously, if you didn’t have MySQL on a computer or laptop, prepare to install MySQL and the Database Editor first, you can use DBeaver, MySQL Workbench or what you usually use for database management.

To make it easier to create a database if you don’t have one, we can also create a MySQL database using Docker by creating a docker-compose.yaml file as below.

version: '3.6'

services:
  mysql:
    container_name: article-mysql
    platform: linux/amd64
    image: mysql
    restart: always
    ports: 
      - "3306:3306"
    volumes:
      - ./.db:/var/lib/mysql
    environment:
      - MYSQL_DATABASE=article
      - MYSQL_ROOT_PASSWORD=root
      - MYSQL_USER=development
      - MYSQL_PASSWORD=d3v3l0pm3nt
    networks:
      - article-network

networks:
  article-network:
    driver: bridge

Then we execute the docker-compose with the command

docker-compose up -d

If successful, we will see the docker that we have up status with the command

docker ps -a
➜ learn-golang-restful git:(main) ✗ docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
ab982e116f72 mysql "docker-entrypoint.s..."   5 minutes ago Up 4 minutes 0.0.0.0:3306->3306/tcp, 33060/tcp article-mysql

Then we enter the database with the user and password in the docker-compose.yaml file and we will see that the database is called article. Next we need to create a table name article with SQL commands like this.

create table articles(
  id integer primary key auto_increment,
  title varchar(255) not null,
  content varchar(255) not null,
  create_at datetime not null,
  update_at datetime not null
) engine = InnoDB;

If you want to try a query, you can go directly to the Database manager by making a query like this.

select * from articles

Which if we execute the results are still empty because we have not filled the data into the table.

comments powered by Disqus