Skip to content
Santekno.com | Level Up Your Engineering Skills
EN
📖 0%
21 Jan 2024 · 2 min read ·Article 80 / 119
Go

03 Creating a Database on MySQL Golang

IH
Ihsan Arif
Writer at Santekno · Backend Engineer

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.

yml
 1version: '3.6'
 2
 3services:
 4  mysql:
 5    container_name: article-mysql
 6    platform: linux/amd64
 7    image: mysql
 8    restart: always
 9    ports: 
10      - "3306:3306"
11    volumes:
12      - ./.db:/var/lib/mysql
13    environment:
14      - MYSQL_DATABASE=article
15      - MYSQL_ROOT_PASSWORD=root
16      - MYSQL_USER=development
17      - MYSQL_PASSWORD=d3v3l0pm3nt
18    networks:
19      - article-network
20
21networks:
22  article-network:
23    driver: bridge

Then we execute the docker-compose with the command

bash
1docker-compose up -d

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

bash
1docker ps -a

bash
1➜ learn-golang-restful git:(main) ✗ docker ps -a
2CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
3ab982e116f72 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.

sql
1create table articles(
2  id integer primary key auto_increment,
3  title varchar(255) not null,
4  content varchar(255) not null,
5  create_at datetime not null,
6  update_at datetime not null
7) engine = InnoDB;

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

sql
1select * from articles

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

Related Articles

💬 Comments