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.
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: bridgeThen we execute the docker-compose with the command
1docker-compose up -dIf successful, we will see the docker that we have up status with the command
1docker ps -a1➜ 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-mysqlThen 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.
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.
1select * from articlesWhich if we execute the results are still empty because we have not filled the data into the table.