Post

리눅스 서버(12) - DATABASE

리눅스 서버(12) - DATABASE

2023 02 23 강의 노트


Maria DB


  • DB software == Exel software
  • DB == Excel file
  • Table == Excel file sheet
  • Column, Row == Excel file sheet의 열, 행

SQL(Structed Query Language)

서버 종류

  • SQL 서버 : (정규화) RDBMS                ->   Oracle, MS-SQL, MySQL, IBM DB2무료: MariaDB …
  • NoSQL 서버 : (반정규화, 비정규화)     ->   MongoDB, Redis

    명령 종류

  • DDL   :   create,   drop,   alter
  • DML   :   select,   insert,   update,   delete
  • DCL   :   grant,   revoke,   commit,   rollback

    대표적인 DB Listner port

  • Oracle : 1521/tcp
  • MS-SQL : 1433/tcp
  • MYSQL/MariaDB : 3306/tcp
  • Postgre SQL : 5432/tcp
  • MongoDB : 27017/tcp
  • Redis : 6379/tcp

데이터를 관리하는 4가지 기본적인 기능 - CRUD

  • Create
  • Read
  • Update
  • Delete

DBMS 종류

  • HDBMS (2세대, 계층형)
  • NDBMS (3세대, 네트워크형)
  • RDBMS (4세대, 관계형)
  • ODBMS (5세대, 객체 지향)

TABLE 관리

  • 정규화
  • 비정규화
  • 반정규화

Maria db 설치

1
2
3
4
5
6
7
8
yum -y intall mariadb-server # 패키지 설치
systemctl enable --now mariadb # 서비스 기동 
mysql_secure_installation # 초기 설정
# 초기 암호는 없으므로 엔터, 그 후 자기가 원하는 암호 설정
# 그리고 설명 보고 원하는 건 y,n 해주면 됨
firewall-cmd --permanent --add-service=mysql # 방화벽 추가
firewall-cmd --reload # 방화벽 등록
firewall-cmd --list-all # 방화벽 리스트

DB 서버 설정 + 실습

  • 패키지 : mariadb-server, mariadb
  • 데몬 & 포트 & 프로토콜 : mysqld(3306/tcp)
  • 주 설정 파일 : /etc/my.cnf ($HOME/.my.cnf가 먼저임)
  • 하위 설정 파일 : /etc/my.cnf.d/*.cnf
  • 서비스 : mariadb.service
  • DATA directory : /var/lib/mysql
  • Log directory : /var/log/mariadb/mariadb.log

기본 설정 확인

cat mariadb-server.cnf db 포트를 여러개 써야하는 경우도 있고 바꿔서 써야 하는 경우도 있는데 이때 포트 번호를 지정해주면 된다.
skip-networking=0 # 모든 클라이언트에서 접속 가능
bind-address=0.0.0.0 # DB 서버의 모든 IP에 대해서 수신 대기

기초 커맨드
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
/* console clear */
<ctrl+L>
\! clear
system clear
/* system 명령어는 shell 명령어를 실행하게 해줌 */

help contents /* 카테고리 보기 */
help Functions /* 카테고리 보기 */
help String Functions /* 종류 보기 */
help concat : /* 해당 설정과 예제 보기 */

/* 접속 끊기 */
exit
quit
\q

DB 관리

1
2
3
4
show databases; /* db 보기 */
use dbname; /* DB 선택 */
create database testdb; /* DB 생성 */
drop database testdb; /* DB 삭제 */

DB table 관리

1
2
3
4
5
6
7
8
show tables; /* table 목록 보기 */
desc tablename; /* table 구조 보기(1) */
describe tablename; /* table 구조 보기(2) */
explain tablename; /* table 구조 보기(3) */
create table testname('항목1' '변수형', '항목2' '변수형', '항목3' '변수형' ...); 
/* table 생성 참고로 영어의 경우 quotation 빼야함*/ 
rename table tablenameOLD to tablenameNEW; /* table 이름 바꾸기 */
drop table tablename; /* table 삭제 */

DB contents 관리

1
2
3
4
5
6
7
8
9
10
11
/* 데이터 확인 */
select * from tablename; 
select field1 from tablename;
select field1, field2 from tablename;
select * from tablename\G; /* 가로로 보기 */
/* 데이터 입력 */
insert into tablename (field1, field2, field3, ...)value('value1','value2','value3'...) 
/* 데이터 업데이트 */
update table tablename set field='value', ... where field='condition' 
/* 데이터 삭제 */
delete from tablename where field='condition'

사용자 관리

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
/* 사용자 생성 */
create user '사용자'@'호스트ip' identified by 'password'
flush privileges;
/* >> ip쓸 때 % 뜻은 '모두'란 뜻이다 */
/* 사용자 암호 변경 */
alter user user@hostip indentified by 'password'
/* 사용자 계정에 대한 권한 부여*/
 grant all privileges on DB.TABLE to user@hostip;
/* 사용자 계정에 대한 권한 박탈 */
revoke privilege_name on db.table from user@hostip;
/* 사용자 권한 확인 */
show grants; /* 자기꺼 */
show grants for 'user'@'hostip';
select * from mysql.user;
/* 사용자 삭제 */
drop user 사용자@호스트;

참고1 사용자 생성 + 암호

create user user1 indentified by ‘password’;
alter user user1 identified by ‘1234’;

참고2 root 암호 초기화

참고페이지
systemctl stop mariadb
mysqld_safe –skip-grant-tables &
mysql -u root 하면 바로 접속 가능함
alter user root@localhost identified by ‘password’;
flush privileges;
exit
mysqladmin -u root -p shutdown 치면 mysqld_safe가 내려감
systemctl start mariadb
mysql -u root -p 새로 접속

  • 장애 처리
문제 DB client해결 DB server
mysql -h server방화벽(3306/tcp)
-P 3306/etc/my.cnf.d/*.conf의 bind address/skip-networking 보기
-u remoteuser -p사용자 이름 체계
password missing암호 똑바로 입력하기
 사용자 권한 입력하기
 ex) grant privileges …

백업 복구

Backup Target : /var/lib/mysql

  • 논리적 백업
    1
    2
    3
    4
    5
    6
    7
    8
    
    # inventory db에대해 백업 받는 경우
    mysqldump -u root -p inventory > /백업받을폴더/백업받을파일
    # 모든 db에 대해 백업 받는 경우
    mysqldump -u root -p --all-databases > /백업받을폴더/백업받을파일
    # 일부 db 복원
    mysql -u root -p DBNAME < /백업받을폴더/백업받을파일
    # 모든 db에 대해 복원
    mysql -u root -p < /백업받을폴더/백업받을파일
    

WEB-DB 연동

부록

  • sql injection cheat sheet
    cheat sheet는 정리본이라고 생각하면 좋음
    참고
  • MySQL Sample Database로 실습
    튜토리얼
This post is licensed under CC BY 4.0 by the author.