회원가입∴아이디/비번찾기
홈으로


[MySQL - 데이터 백업과 복구]MySQL의 mysqldump 백업과 바이너리 백업 및 복구 방법
15년 전
MySQL의 데이터를 백업하는 방법은 크게 두가지로 분류 할 수 있다.

1. mysqldump를 이용한 text타입의 백업 방법.
2. 데이터파일 자체를 복사하는 백업 방법.

두가지 방법모두 장단점이 있으므로 용도와 필요에 맞게 사용하는 것이 좋다.



1. mysqldump를 이용한 백업(출처 : http://dev.mysql.com/doc/refman/5.1/en/mysqldump.html)

 mysqldump는 Igor Romanenko라는 사람이 만든 백업 프로그램이다. 이는 database나 database의 일부를 백업하는 목적이나 다른 시스템으로 옮길때 사용된다. 그리고 원하는 분리 문자를 넣을 수 있어 CSV파일 등으로 만들 수 있으며, XML포맷으로 만들 수도 있다.
 굉장히 많은 옵션들을 제공하고 있는 만큼 사용하는 방법과 용도 또한 여러가지이다. 먼저 가장 기본적인 사용법 부터 알아 보자. 아래에 옵션표를 첨부할 것이다.

1) database백업
shell> mysqldump -u user -p 백업할 db_name > 파일명
shell> mysqldump -u comnic -p database1 > database1_20090321000000.sql
 

위는 comnic이라는 유저로 database1이라는 database를 database1_20090321000000.sql파일로 백업하라는 내용이다.


2) table백업
shell> mysqldump -u user -p 백업할 db_name table_name > 파일명
shell> mysqldump -u comnic -p database1 table1 > table1_20090321000000.sql
 

위는 comnic이라는 유저로 database1의 table1이라는 table을 table1_20090321000000.sql파일로 백업하라는 내용이다.


3) Table 구조만 백업
shell> mysqldump --no-data -u user -p 백업할 db_name > 파일명
shell> mysqldump --no-data -u comnic -p database1 > 20090321000000.sql
 

위는 comnic이라는 유저로 database1의 table구조를 20090321000000.sql파일로 백업하라는 내용이다.
--no-data 옵션은 create table문장만을 백업하기를 원할때 유용한다.


4) Table별로 백업 파일 생성
shell> mysqldump -u user -p --tab=백업Path 백업할 db_name
shell> mysqldump -u comnic -p --tab=/backup database1
 

/backup이라는 폴더에 table마다 각각 tbl_name.sql파일과 tbl_name.txt파일을 생성한다. 이는 Table의 구조와 데이터를 분리 하여 백업하는 것을 의미 한다. .sql파일은 구조를 .txt파일은 데이터를 저장한다. 이때 분리 문자가 사용되는데 기본적을 tab이 사용된다. 이 분리문자를 변경하면 원하는 분리 문자로 구성된 파일을 만들 수 있다.


5) CSV파일로 백업 및 다른 분리 문자로 백업
shell> mysqldump -u user -p --tab=백업Path  --fields-terminated-by='분리문자' 백업할 db_name
shell> mysqldump -u comnic -p --tab=/backup --fields-terminated-by=',' database1
 

기본적인 분리문자인 tab대신 ,를 사용해 백업을 한다. 즉, CSV파일로 생성된다.


6) XML포맷으로 백업
shell> mysqldump -u user -p --xml 백업할 db_name > 파일명
shell> mysqldump -u comnic -p --xml database1 > 20090321000000.xml
 

 

2. 복구하기

 위와 같은 방법들로 백업된 파일을 복구하는 방법은 아래와 같다.

 
shell> mysql -u user -p db_name < 파일명
shell> mysql -u comnic -p database1 < 20090321000000.sql
 

복구시 한글이 깨지는 경우가 종종 있다. 그럴때는 아래와 같이 --default-character-set 옵션을 사용해 복구한다.
 
 
shell> mysql -u user -p --default-character-set=euckr db_name < 파일명
 



3. 바이너리 백업(파일 복사 혹은 압축을 이용)

 MySQL을 사용하는 사용자들은 흔히 data파일을 복사하는 방식의 백업이 쉽고 빠르다고 얘기들을 한다. 나 또한 그런식으로 백업을 많이 하고 있다. shell 프로그램으로 자동 백업 후 다른 시스템으로 ftp를 이용해 옮기는 방법으로 자동화를 많이 사용 하고 있다. shell를 이용한 자동화 부분은 다음에 다루도록 하겠다.

1) 복사 및 압축을 이용한 백업
 cp와 tar를 이용하면 쉽게 백업을 할 수 있다. 복사전에 lock을 걸어주고 복사가 끝난후 unlock를 꼭 해 주어야 한다.
복구는 파일 그냥 다시 복사 해 주면 된다. 데이터를 옮기는 과정이라면 복사 이후 추가된 데이터를 다시 추가 해 주어야 한다.

2) mysqlhotcopy를  이용한 백업(출처:http://dev.mysql.com/doc/refman/5.1/en/mysqlhotcopy.html)
 DB전체를 백업할때는 mysqldump보다 이를 이용하면 더욱 빠르게 백업을 할 수 있다고 한다.
mysqlhotcopy는 LOCK TABLES, FLUSH TABLES 그리고 cp나 scp를 이용해 파일을 생성한다.
주의 할점은  MyISAM과 ARCHIVE table만 가능하다는 것이다.
사용방법은 다은과 같다.

 
shell> mysqlhotcopy db_name [/path/to/new_directory]
shell> mysqlhotcopy db_name_1 ... db_name_n /path/to/new_directory
 

정규식을 이용하는 방법도 있다.

 
shell> mysqlhotcopy db_name./regex/
shell> mysqlhotcopy db_name./~regex/
 




첨부.1

 
Format Config File Description Introduction
--add-drop-database add-drop-database Add a DROP DATABASE statement before each CREATE DATABASE statement  
--add-drop-table add-drop-table Add a DROP TABLE statement before each CREATE TABLE statement  
--add-locks add-locks Surround each table dump with LOCK TABLES and UNLOCK TABLES statements  
--all-databases all-databases Dump all tables in all databases  
--all-tablespaces all-tablespaces Adds to a table dump all SQL statements needed to create any tablespaces used by an NDB Cluster table 5.1.6
--allow-keywords allow-keywords Allow creation of column names that are keywords  
--comments comments Add comments to the dump file  
--compact compact Produce less verbose output  
--compatible=name[,name,...] compatible Produce output that is more compatible with other database systems or with older MySQL servers  
--complete-insert complete-insert Use complete INSERT statements that include column names  
--create-options create-options Include all MySQL-specific table options in the CREATE TABLE statements  
--databases databases Dump several databases  
--debug[=debug_options] debug Write a debugging log  
--debug-check debug-check Print debugging information when the program exits 5.1.21
--debug-info debug-info Print debugging information, memory and CPU statistics when the program exits 5.1.14
--delayed-insert delayed-insert Write INSERT DELAYED statements rather than INSERT statements  
--delete-master-logs delete-master-logs On a master replication server, delete the binary logs after performing the dump operation  
--disable-keys disable-keys For each table, surround the INSERT statements with disable and enable keys statements  
--dump-date dump-date Include dump date in "Dump completed on" comment if --comments is given 5.1.23
-E events Dump events from the dumped databases  
--extended-insert extended-insert Use multiple-row INSERT syntax that include several VALUES lists  
--fields-enclosed-by=string fields-enclosed-by This option is used with the -T option and has the same meaning as the corresponding clause for LOAD DATA INFILE  
--fields-escaped-by fields-escaped-by This option is used with the -T option and has the same meaning as the corresponding clause for LOAD DATA INFILE  
--fields-optionally-enclosed-by=string fields-optionally-enclosed-by This option is used with the -T option and has the same meaning as the corresponding clause for LOAD DATA INFILE  
--fields-terminated-by=string fields-terminated-by This option is used with the -T option and has the same meaning as the corresponding clause for LOAD DATA INFILE  
--lock-all-tables first-slave Deprecated. Now renamed to --lock-all-tables  
--flush-logs flush-logs Flush the MySQL server log files before starting the dump  
--flush-privileges flush-privileges Emit a FLUSH PRIVILEGES statement after dumping the mysql database  
--help   Display help message and exit  
--hex-blob hex-blob Dump binary columns using hexadecimal notation (for example, 'abc' becomes 0x616263)  
--ignore-table=db_name.tbl_name ignore-table Do not dump the given table  
--insert-ignore insert-ignore Write INSERT statements with the IGNORE option  
--lines-terminated-by=string lines-terminated-by This option is used with the -T option and has the same meaning as the corresponding clause for LOAD DATA INFILE  
--lock-all-tables lock-all-tables Lock all tables across all databases  
--lock-tables lock-tables Lock all tables before dumping them  
--log-error=file_name log-error Append warnings and errors to the named file 5.1.18
--master-data[=value] master-data Write the binary log file name and position to the output  
--max_allowed_packet=value max_allowed_packet The maximum packet length to send to or receive from the server  
--net_buffer_length=value net_buffer_length The buffer size for TCP/IP and socket communication  
--no-autocommit no-autocommit Enclose the INSERT statements for each dumped table within SET autocommit = 0 and COMMIT statements  
--no-create-db no-create-db This option suppresses the CREATE DATABASE statements  
--no-create-info no-create-info Do not write CREATE TABLE statements that re-create each dumped table  
--no-data no-data Do not write any table row information (that is, do not dump table contents)  
--no-set-names no-set-names Turn off complete-insert  
--opt opt This option is shorthand; it is the same as specifying --add-drop-table --add-locks --create-options --disable-keys --extended-insert --lock-tables --quick --set-charset.  
--order-by-primary order-by-primary Sorts each table's rows by its primary key, or by its first unique index  
--password[=password] password The password to use when connecting to the server  
--pipe   On Windows, connect to server via a named pipe  
--port=port_num port The TCP/IP port number to use for the connection  
--quick quick Retrieve rows for a table from the server a row at a time  
--quote-names quote-names Quote database, table, and column names within backtick characters  
--replace replace Write REPLACE statements rather than INSERT statements  
--result-file=file result-file Direct output to a given file  
-R routines Dump stored routines (procedures and functions) from the dumped databases  
--set-charset set-charset Add SET NAMES default_character_set to the output  
--single-transaction single-transaction This option issues a BEGIN SQL statement before dumping data from the server  
--skip-add-drop-table skip-add-drop-table Do not add  
--skip-add-locks skip-add-locks Do not add locks  
--skip-comments skip-comments Do not add comments to the dump file  
--skip-compact skip-compact Turn off compact  
--skip-disable-keys skip-disable-keys Do not disable keys  
--skip-extended-insert skip-extended-insert Turn off extended-insert  
--skip-opt skip-opt Turn off the options set by opt  
--skip-quick skip-quick Do not retrieve rows for a table from the server a row at a time  
--skip-quote-names skip-quote-names Turn off quote names  
--skip-set-charset skip-set-charset Suppress the SET NAMES statement  
--skip-triggers skip-triggers Turn off triggers  
--skip-tz-utc skip-tz-utc Turn off tz-utc  
--ssl-ca=file_name ssl-ca The path to a file that contains a list of trusted SSL CAs  
--ssl-capath=directory_name ssl-capath The path to a directory that contains trusted SSL CA certificates in PEM format  
--ssl-cert=file_name ssl-cert The name of the SSL certificate file to use for establishing a secure connection  
--ssl-cipher=cipher_list ssl-cipher A list of allowable ciphers to use for SSL encryption  
--ssl-key=file_name ssl-key The name of the SSL key file to use for establishing a secure connection  
--ssl-verify-server-cert ssl-verify-server-cert The server's Common Name value in its certificate is verified against the host name used when connecting to the server  
--tab=path tab Produce tab-separated data files  
--tables tables Override the --databases or -B option  
--triggers triggers Dump triggers for each dumped table  
--tz-utc tz-utc Add SET TIME_ZONE='+00:00' to the dump file  
--verbose   Verbose mode  
--version   Display version information and exit  
--where='where_condition' where Dump only rows selected by the given WHERE condition  
--xml xml Produce XML output
추천추천 : 644 추천 목록
번호 제목
2,891
입력 필드에서 특정단어(예:#err)가 포함되었을 때 실시간 감지 및 경고창 띄우기
2,890
데이터베이스 최적화와 쿼리 효율성을 높이 검색 성능을 개선하는 방법
2,889
간단한 게시판 만들기
2,888
PHP의 php.ini 파일에서 설정할 수 있는 주요 항목들을 카테고리별로 정리
2,887
유튜브 동영상의 썸네일 이미지를 체크하여 유효한 영상이아닐때 연결된 체크박스를 자동으로 체크
2,886
이미지 URL이 유효하지 않을 때, 해당 이미지와 연결된 체크박스를 자동으로 체크
2,885
HTTPS로 접속한 사용자를 강제로 HTTP로 리디렉션 하려면
2,884
PHP에서 MP3 파일을 직접 읽고 스트리밍 하기
2,883
현재 페이지가 location.reload()에 의해 새로고침되었는지
2,882
텍스트 파일을 읽고, 각 줄의 끝에서 6글자를 삭제한 후, 결과를 새로운 파일에 저장합니다.
2,881
cURL을 사용하여 리다이렉트를 따라가 최종 URL 가져오기
2,880
[PHP] $_SERVER 환경변수
2,879
10진수 <-> 16진수 변환기 PHP소스
2,878
텍스트에 직접 그라데이션 색상을 적용하려면?
2,877
CSS를 사용하여 요소의 내용물에 따라 width를 조정하는 방법
2,876
웹서버 ip 확인
2,875
웹호스팅의 절대경로를 확인
2,874
input 입력 필드 앞뒤 공백 실시간 제거
2,873
Placeholder 포커스시 감추기
2,872
MySQL 중복된 데이터를 삭제
2,871
MySQL 중복 데이터 확인
2,870
sessionStorage.getItem 와 sessionStorage.setItem
2,869
제이쿼리 랜덤으로 배경색 변경
2,868
preg match에 관한 정규식
2,867
Stream an audio file with MediaPlayer 오디오 파일 스트리밍 하기
2,866
Audio Streaming PHP Code
2,865
PHP $ SERVER 환경 변수 정리
2,864
Vimeo (비메오) API 를 사용하여 플레이어 컨트롤하기
2,863
iframe 사용시 하단에 발생하는 공백 제거방법
2,862
아이프레임(iframe) 전체화면 가능하게 하기
목록
뮤직트로트 부산광역시 부산진구 가야동 ㅣ 개인정보취급방침ㅣ모바일버전
Copyright ⓒ musictrot All rights reserved.