크래프톤정글/정글생활

[DB] MySQL 에 정보 저장하고 검색하기

아람2 2025. 1. 5. 20:17
반응형

프로젝트를 진행하면서, 로그인한 JWT 를 가져와서 해독하고, 그 정보를 기반으로 유저를 파싱하려고 한다 

MySQL 사용하는 법이 헷갈려서 정리해둔다
MySQL 설치는 여기에 정리해놨고 https://helloahram.tistory.com/172

Docker Image Build 도 여기에 정리했다 https://helloahram.tistory.com/197

 

기존에 공부하면서 사용했던 MySQL Database 를 싹 다 지우고 진행할 예정이다 

나는 Docker 에 MySQL 을 설치해놨다, 그래서 docker ps 로 이름을 먼저 찾아준다 

ahram@AhramuicBookPro  ~  docker ps
CONTAINER ID     IMAGE          COMMAND                 NAMES
[CONTAINER_ID]   custom-mysql   "docker-entrypoint.s…"  mysql-container

 

그리고 해당 컨테이너를 실행해준다 

ahram@AhramuicBookPro  ~  docker exec -it mysql-container /bin/bash
bash-5.1#

 

bash 에 들어왔으니 아래 명령어로 MySQL 에 진입한다 (DB 계정 ID 가 ahram 이다)

참고로 -u 는 사용자를 지정하는 옵션이고, -p 는 비밀번호를 입력하라는 요청을 하는 옵션이다 

bash-5.1# mysql -u ahram -p
Enter password:
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 172
Server version: 8.0.40 MySQL Community Server - GPL

Copyright (c) 2000, 2024, Oracle and/or its affiliates.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql>

 

아니면 로컬에서 한 줄로 편하게 접속할 수 있다, 개인적으로는 이게 더 편하다 

ahram@AhramuicBookPro  ~  docker exec -it mysql-container mysql -u ahram -p
Enter password:
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 267
Server version: 8.0.40 MySQL Community Server - GPL

Copyright (c) 2000, 2024, Oracle and/or its affiliates.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql>

 

show databases; 명령어로 Database 를 볼 수 있다 

mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| ahram_DB           |
| information_schema |
| performance_schema |
+--------------------+
3 rows in set (0.05 sec)

mysql>

 

USE 로 삭제하려는 DB 를 선택하고, DROP database 로 삭제해주면 삭제 끝!

mysql> USE ahram_DB
Database changed
mysql> DROP database ahram_DB
    -> ;
Query OK, 8 rows affected (0.25 sec)

mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| performance_schema |
+--------------------+
2 rows in set (0.01 sec)

mysql>

참고로, USE 를 안 해주면 아래와 같은 ERROR MSG 가 출력된다 

ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'ahram_DB' at line 1

 


 

이제 깔끔하게 DB 를 다시 만들어준다 

UTF8 을 기반으로 하는 DB 를 만들려면 아래와 같이 작성하면 된다 

mysql> CREATE DATABASE [생성할DB이름] DEFAULT CHARACTER SET UTF8;
mysql> CREATE DATABASE grim DEFAULT CHARACTER SET UTF8;
Query OK, 1 row affected, 1 warning (0.03 sec)

mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| ahramDB            |
| grim               |
| information_schema |
| mysql              |
| performance_schema |
| sys                |
+--------------------+
6 rows in set (0.01 sec)

 

use [DB이름] 으로 만들어준 DB 에 들어가서 Table 과 Column 을 만들어준다 

나는 id 과 이름이 있는, user 라는 테이블을 만들었고, 한글을 사용하기 위해 utf8mb4 로 설정해 줬다 

mysql> use grim
Database changed
mysql> show tables;
Empty set (0.00 sec)

mysql> CREATE TABLE user (
    -> id INT PRIMARY KEY AUTO_INCREMENT,
    -> name VARCHAR(255)
    -> ) DEFAULT CHARACTER SET utf8mb4;
Query OK, 0 rows affected (0.05 sec)

mysql> show tables;
+----------------+
| Tables_in_grim |
+----------------+
| user           |
+----------------+
1 rows in set (0.02 sec)

mysql>

🐣 이미 만들어진 Table 에 Column 을 추가할 때는 ALTER TABLE 사용! 🐣

mysql> ALTER TABLE user
    -> ADD COLUMN name VARCHAR(255) NOT NULL;
Query OK, 0 rows affected (0.12 sec)
Records: 0  Duplicates: 0  Warnings: 0

 

값을 여러 개 넣고 싶을 때는 쉼표로 구분해서, INSERT INTO 를 쓴다 

mysql> INSERT INTO user VALUES (NULL, 'A'), (NULL, 'B');
Query OK, 2 rows affected (0.02 sec)
Records: 2  Duplicates: 0  Warnings: 0

mysql> select * from user;
+----+------+
| id | name |
+----+------+
|  1 | A    |
|  2 | B    |
+----+------+
2 rows in set (0.00 sec)

mysql>

 

🐣 내용을 삭제하고 싶으면 DELETE FROM 을 쓴다 🐣

DELETE FROM table_name WHERE 조건;

 

전시회에 들어갈 게시글은 id, user_id, title 을 넣어준다 

mysql> CREATE TABLE painting (
    -> id INT AUTO_INCREMENT PRIMARY KEY,
    -> user_id INT,
    -> title VARCHAR(255) NOT NULL);
Query OK, 0 rows affected (0.07 sec)

mysql> show tables;
+----------------+
| Tables_in_grim |
+----------------+
| painting       |
| user           |
+----------------+
2 rows in set (0.01 sec)

mysql>

DESCRIBE 로 확인하니, 잘 들어갔다 

mysql> DESCRIBE painting;
+---------+--------------+------+-----+---------+----------------+
| Field   | Type         | Null | Key | Default | Extra          |
+---------+--------------+------+-----+---------+----------------+
| id      | int          | NO   | PRI | NULL    | auto_increment |
| user_id | int          | YES  |     | NULL    |                |
| title   | varchar(255) | NO   |     | NULL    |                |
+---------+--------------+------+-----+---------+----------------+
3 rows in set (0.03 sec)

mysql>

 

2번 USER 의 그림 두 개를 만들어준다 

mysql> INSERT INTO painting VALUES (1, 2, 'flower');
Query OK, 1 row affected (0.02 sec)

mysql> INSERT INTO painting VALUE (NULL, 2, 'butterfiles');
Query OK, 1 row affected (0.05 sec)

mysql> select * from painting;
+----+---------+-------------+
| id | user_id | title       |
+----+---------+-------------+
|  1 |       2 | flower      |
|  2 |       2 | butterfiles |
+----+---------+-------------+
2 rows in set (0.00 sec)

mysql>

3번 user 의 그림도 두 개 만들어준다 

mysql> INSERT INTO painting VALUES (NULL, 3, 'tiger'),
    -> (NULL, 3, 'lion');
Query OK, 2 rows affected (0.02 sec)
Records: 2  Duplicates: 0  Warnings: 0

mysql> select * from painting;
+----+---------+-------------+
| id | user_id | title       |
+----+---------+-------------+
|  1 |       2 | flower      |
|  2 |       2 | butterfiles |
|  3 |       3 | tiger       |
|  4 |       3 | lion        |
+----+---------+-------------+
4 rows in set (0.00 sec)

 

특정 user_id 로 검색하고 싶으면 WHERE 을 활용한다 

mysql> SELECT * FROM painting WHERE user_id = 2;
+----+---------+-------------+
| id | user_id | title       |
+----+---------+-------------+
|  1 |       2 | flower      |
|  2 |       2 | butterfiles |
+----+---------+-------------+
2 rows in set (0.03 sec)

 

user Table 에 PhoneNumber Column 을 추가하고 번호를 넣을 때는

ALTER TABLE 로 column 을 만들어주고 UPDATE 로 번호를 추가할 수 있다 

mysql> select * from user;
+----+------+
| id | name |
+----+------+
|  1 | A    |
|  2 | B    |
|  3 | C    |
+----+------+
3 rows in set (0.00 sec)

mysql> ALTER TABLE user
    -> ADD COLUMN PhoneNumber VARCHAR(255) NOT NULL;
Query OK, 0 rows affected (0.12 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> select * from user;
+----+------+-------------+
| id | name | PhoneNumber |
+----+------+-------------+
|  1 | A    |             |
|  2 | B    |             |
|  3 | C    |             |
+----+------+-------------+
3 rows in set (0.00 sec)

mysql> UPDATE user
    -> SET PhoneNumber = '010-1234-5678'
    -> WHERE id = 1;
Query OK, 1 row affected (0.02 sec)
Rows matched: 1  Changed: 1  Warnings: 0

mysql> select * from user;
+----+------+---------------+
| id | name | PhoneNumber   |
+----+------+---------------+
|  1 | A    | 010-1234-5678 |
|  2 | B    |               |
|  3 | C    |               |
+----+------+---------------+
3 rows in set (0.01 sec)

mysql>
반응형

'크래프톤정글 > 정글생활' 카테고리의 다른 글

[회고] 크래프톤 정글 7기 회고  (0) 2025.01.22
[회고] 나만무 중간 회고  (0) 2025.01.07
Spring 용어 정리  (0) 2024.12.24
[나만무] AWS 환경 구성  (2) 2024.12.21
[나만무] 기획 확정  (0) 2024.12.20