programing

mysqldump 출력을 작은 파일로 분할하려면 어떻게 해야 합니까?

sourcejob 2022. 11. 5. 17:32
반응형

mysqldump 출력을 작은 파일로 분할하려면 어떻게 해야 합니까?

MySQL 데이터베이스 간에 전체 테이블을 이동해야 합니다.두 번째 것에는 풀 액세스 권한이 없습니다.phpMyAdmin 액세스만 가능합니다.2MB 미만의 sql 파일만 업로드(압축)할 수 있지만 첫 번째 데이터베이스 테이블의 mysqldump에서 압축된 출력이 10MB보다 큽니다.

mysqldump 출력을 더 작은 파일로 분할할 수 있는 방법이 있습니까?리모트 서버에 파일을 되돌릴 수 없기 때문에 split(1)을 사용할 수 없습니다.

아니면 제가 놓친 다른 해결책이 있나요?

편집

--syslog-insert=첫 번째 포스터에서 제시된 mysqldump에 대한 FALSE 옵션은 적절한 --lines 옵션을 사용하여 split(1)을 호출하는 경우 Import 가능한 파일로 분할할 수 있는 .sql 파일을 생성합니다.시행착오를 통해 bzip2가 .sql 파일을 20배 압축한다는 것을 알게 되었기 때문에 대략 40MB에 해당하는 SQL 코드 줄 수를 알아내야 했습니다.

이 bash 스크립트는 1개의 데이터베이스의 덤프 파일을 각 테이블 및 csplit을 사용하여 다른 파일로 분할하고 그에 따라 이름을 지정합니다.

#!/bin/bash

####
# Split MySQL dump SQL file into one file per table
# based on https://gist.github.com/jasny/1608062
####

#adjust this to your case:
START="/-- Table structure for table/"
# or 
#START="/DROP TABLE IF EXISTS/"


if [ $# -lt 1 ] || [[ $1 == "--help" ]] || [[ $1 == "-h" ]] ; then
        echo "USAGE: extract all tables:"
        echo " $0 DUMP_FILE"
        echo "extract one table:"
        echo " $0 DUMP_FILE [TABLE]"
        exit
fi

if [ $# -ge 2 ] ; then
        #extract one table $2
        csplit -s -ftable $1 "/-- Table structure for table/" "%-- Table structure for table \`$2\`%" "/-- Table structure for table/" "%40103 SET TIME_ZONE=@OLD_TIME_ZONE%1"
else
        #extract all tables
        csplit -s -ftable $1 "$START" {*}
fi
 
[ $? -eq 0 ] || exit
 
mv table00 head
 
FILE=`ls -1 table* | tail -n 1`
if [ $# -ge 2 ] ; then
        # cut off all other tables
        mv $FILE foot
else
        # cut off the end of each file
        csplit -b '%d' -s -f$FILE $FILE "/40103 SET TIME_ZONE=@OLD_TIME_ZONE/" {*}
        mv ${FILE}1 foot
fi
 
for FILE in `ls -1 table*`; do
        NAME=`head -n1 $FILE | cut -d$'\x60' -f2`
        cat head $FILE foot > "$NAME.sql"
done
 
rm head foot table*

https://gist.github.com/jasny/1608062를 기반으로 합니다.
및 https://stackoverflow.com/a/16840625/1069083 를 참조해 주세요.

먼저 스키마를 덤프합니다(확실히 2Mb가 맞지요?)

mysqldump -d --all-databases 

복원해 주세요.

이후 별도의 insert 문에 데이터만 덤프되므로 리모트 서버에 연결하지 않고도 파일을 분할하여 복원할 수 있습니다.

mysqldump --all-databases --extended-insert=FALSE --no-create-info=TRUE

mysqldump에서 추출할 때 사용할 수 있는 수많은 옵션이 포함된 이 뛰어난 mysqldumpsplitter 스크립트가 있습니다.

레시피를 여기에 복사하여 고객님의 사례를 선택합니다.

1) mysqldump에서 단일 데이터베이스 추출:

sh mysqldumpsplitter.sh --source filename --extract DB --match_str database-name

위의 명령어는 지정된 "filename" sql 파일에서 지정된 데이터베이스의 sql을 생성하여 압축된 형식으로 database-name.sql.gz에 저장합니다.

2) mysqldump에서 단일 테이블을 추출합니다.

sh mysqldumpsplitter.sh --source filename --extract TABLE --match_str table-name

위의 명령어는 지정된 "filename" mysqldump 파일에서 지정된 테이블의 sql을 생성하여 압축된 형식으로 database-name.sql.gz에 저장합니다.

3) mysqldump에서 정규 표현과 일치하는 테이블을 추출합니다.

sh mysqldumpsplitter.sh --source filename --extract REGEXP --match_str regular-expression

위의 명령어는 지정된 "filename" mysqldump 파일에서 지정된 정규 표현과 일치하는 테이블의 sql을 생성하여 개별 table-name.sql.gz에 압축된 형식으로 저장합니다.

4) mysqldump에서 모든 데이터베이스를 추출합니다.

sh mysqldumpsplitter.sh --source filename --extract ALLDBS

위의 명령어는 지정된 "filename" mysqldump 파일에서 모든 데이터베이스를 추출하여 압축 형식으로 개별 database-name.sql.gz에 저장합니다.

5) mysqldump에서 모든 테이블을 추출합니다.

sh mysqldumpsplitter.sh --source filename --extract ALLTABLES

위의 명령어는 지정된 "filename" mysqldump 파일에서 모든 테이블을 추출하여 압축 형식으로 개별 table-name.sql.gz에 저장합니다.

6) mysqldump에서 테이블 목록을 추출합니다.

sh mysqldumpsplitter.sh --source filename --extract REGEXP --match_str '(table1|table2|table3)'

위의 명령어는 지정된 "filename" mysqldump 파일에서 테이블을 추출하여 압축 형식으로 개별 table-name.sql.gz에 저장합니다.

7) 압축된 mysqldump에서 데이터베이스를 추출합니다.

sh mysqldumpsplitter.sh --source filename.sql.gz --extract DB --match_str 'dbname' --decompression gzip

위의 명령어는 gzip을 사용하여 filename.sql.gz의 압축을 풀고 "filename.sql.gz"에서 "dbname"이라는 이름의 데이터베이스를 추출하여 out/dbname.sql.gz로 저장합니다.

8) 압축된 mysqldump에서 압축되지 않은 형식으로 데이터베이스를 추출합니다.

sh mysqldumpsplitter.sh --source filename.sql.gz --extract DB --match_str 'dbname' --decompression gzip --compression none

위의 명령어는 gzip을 사용하여 filename.sql.gz의 압축을 풀고 "filename.sql.gz"에서 "dbname"이라는 이름의 데이터베이스를 추출하여 플레인 sql out/dbname으로 저장합니다.sql

9) 다른 폴더에 있는 mysqldump에서 모든 테이블을 추출합니다.

sh mysqldumpsplitter.sh --source filename --extract ALLTABLES --output_dir /path/to/extracts/

위의 명령어는 지정된 "filename" mysqldump 파일에서 모든 테이블을 추출하고 압축 형식의 테이블을 /path/to/extracts/ 아래에 저장된 개별 파일 table-name.sql.gz로 추출합니다.존재하지 않는 경우 스크립트는 /path/to/extracts/ 폴더를 만듭니다.

10) 1개의 데이터베이스에서1개 이상의 테이블을 풀 덤프로 추출합니다.

여러 데이터베이스를 포함하는 풀 덤프가 있고 한 데이터베이스에서 몇 개의 테이블을 추출해야 한다고 가정합니다.

「 」 、 「 」 、 「 」sh mysqldumpsplitter.sh --source filename --extract DB --match_str DBNAME --compression none

을 추출합니다.sh mysqldumpsplitter.sh --source out/DBNAME.sql --extract REGEXP --match_str "(tbl1|tbl2)"할 수 , 를 들어 하다, 하다, 하다, 하다, 하다, 하다, 하다, 하다, 하다, 이렇게 할 수 있습니다.

sh mysqldumpsplitter.sh --source filename --extract DBTABLE --match_str "DBNAME.(tbl1|tbl2)" --compression none

위의 명령어는 DBNAME 데이터베이스에서 현재 디렉토리의 "out" 폴더 아래에 있는 sql 형식으로 tbl1과 tbl2를 모두 추출합니다.

다음과 같이 단일 테이블을 추출할 수 있습니다.

sh mysqldumpsplitter.sh --source filename --extract DBTABLE --match_str "DBNAME.(tbl1)" --compression none

11) 특정 데이터베이스에서 모든 테이블을 추출합니다.

mysqldumpsplitter.sh --source filename --extract DBTABLE --match_str "DBNAME.*" --compression none

위의 명령어는 DBNAME 데이터베이스에서 모든 테이블을 sql 형식으로 추출하여 "out" 디렉토리에 저장합니다.

12) mysqldump 파일의 내용을 나열합니다.

mysqldumpsplitter.sh --source filename --desc

위의 명령어는 덤프 파일에서 데이터베이스와 테이블을 나열합니다.

나중에 zcat filename.sql.gz | mysql - uUSER - p - hHOSTNAME 파일을 로드하도록 선택할 수 있습니다.

  • 또한 더 크다고 생각되는 단일 테이블을 추출한 후에는 linux split 명령과 행 수를 사용하여 덤프를 더 분할할 수 있습니다. split -l 10000 filename.sql

  • 즉, (더 자주) 필요한 경우 mydumper를 사용하면 분할할 필요가 없는 개별 덤프를 생성할 수 있습니다.

두 번째 서버에 액세스할 수 없다고 합니다.그러나 테이블이 있는 첫 번째 서버에 대한 셸 액세스 권한이 있는 경우 테이블별로 덤프를 분할할 수 있습니다.

for T in `mysql -N -B -e 'show tables from dbname'`; \
   do echo $T; \
   mysqldump [connecting_options] dbname $T \
   | gzip -c > dbname_$T.dump.gz ; \
   done

그러면 각 테이블의 gzip 파일이 생성됩니다.

mysqldump 출력을 다른 파일로 분할하는 다른 방법은 --tab 옵션을 사용하는 것입니다.

mysqldump [connecting options] --tab=directory_name dbname 

여기서 directory_name은 빈 디렉토리의 이름입니다.이 명령어는 각 테이블에 CREATE TABLE 문을 포함하는 .sql 파일과 데이터를 포함하는 .txt 파일을 생성하여 LOAD DATA INFILE을 사용하여 복원합니다.단, phpMyAdmin이 당신의 특별한 제한으로 이 파일들을 처리할 수 있을지는 잘 모르겠습니다.

회신이 늦었지만, 같은 솔루션을 찾고 있던 중, 아래의 Web 사이트에서 다음의 코드를 발견했습니다.

for I in $(mysql -e 'show databases' -s --skip-column-names); do mysqldump $I | gzip > "$I.sql.gz"; done

http://www.commandlinefu.com/commands/view/2916/backup-all-mysql-databases-to-individual-files

이번에는 적절한 파서를 사용하여 SQLDumpSplitter의 새로운 버전을 작성했습니다.INSERT와 같은 많은 값을 가진 멋진 것들을 파일로 분할할 수 있습니다.이것이 멀티 플랫폼입니다.https://philiplb.de/sqldumpsplitter3/

어느 서버에도 ssh 액세스 할 필요가 없습니다.mysql[dump] 고객만 있으면 됩니다.mysql[dump]을 사용하면 데이터베이스를 덤프했다가 다시 가져올 수 있습니다.

PC에서는 다음과 같은 작업을 수행할 수 있습니다.

$ mysqldump - u originaluser - poriginal password - horiginal password | mysql - u newuser - pnewpassword - h newhost newdatabase

이것으로 끝입니다. :-)

이것이 도움이 되기를 바란다

기존 파일을 AWK별로 분할할 수 있습니다.그것은 매우 간단하고 간단하다.

테이블 덤프를 '테이블'별로 분할합니다.

cat dump.sql | awk 'BEGIN {output = "comments"; }
$data ~ /^CREATE TABLE/ {close(output); output = substr($3,2,length($3)-2); }
{ print $data >> output }';

또는 덤프를 '데이터베이스'별로 분할할 수 있습니다.

cat backup.sql | awk 'BEGIN {output="comments";} $data ~ /Current Database/ {close(output);output=$4;} {print $data>>output}';

mysqldump를 사용하여 개별 테이블을 덤프할 수 있습니다.mysqldump database table1 table2 ... tableN

테이블이 너무 크지 않으면 그걸로 충분합니다.그렇지 않으면 큰 테이블에서 데이터를 분할해야 합니다.

유틸리티 bigdump를 추천합니다.여기서 받으실 수 있습니다.http://www.ozerov.de/bigdump.php 이것은 한 번에 전체 라인을 실행하면서 덤프의 실행을 최대한 지연시킵니다.

이것을 시험해 보세요.https://github.com/shenli/mysqldump-hugetable 많은 작은 파일에 데이터가 덤프됩니다.각 파일에는 MAX_RECORDS 레코드 이하가 포함됩니다.이 파라미터는 env.sh 에서 설정할 수 있습니다.

하나의 큰 SQL 덤프 파일을 CREATE TABLE 문마다 하나씩 별도의 파일로 분할하는 Python 스크립트를 작성했습니다.지정한 새 폴더에 파일을 씁니다.출력 폴더를 지정하지 않으면 덤프 파일과 같은 이름의 새 폴더가 같은 디렉토리에 생성됩니다.먼저 파일을 메모리에 쓰지 않고 한 줄 한 줄 작동하기 때문에 대용량 파일에 적합합니다.

https://github.com/kloddant/split_sql_dump_file

import sys, re, os

if sys.version_info[0] < 3:
    raise Exception("""Must be using Python 3.  Try running "C:\\Program Files (x86)\\Python37-32\\python.exe" split_sql_dump_file.py""")

sqldump_path = input("Enter the path to the sql dump file: ")

if not os.path.exists(sqldump_path):
    raise Exception("Invalid sql dump path.  {sqldump_path} does not exist.".format(sqldump_path=sqldump_path))

output_folder_path = input("Enter the path to the output folder: ") or sqldump_path.rstrip('.sql')

if not os.path.exists(output_folder_path):
    os.makedirs(output_folder_path)

table_name = None
output_file_path = None
smallfile = None

with open(sqldump_path, 'rb') as bigfile:
    for line_number, line in enumerate(bigfile):
        line_string = line.decode("utf-8")
        if 'CREATE TABLE' in line_string.upper():
            match = re.match(r"^CREATE TABLE (?:IF NOT EXISTS )?`(?P<table>\w+)` \($", line_string)
            if match:
                table_name = match.group('table')
                print(table_name)
                output_file_path = "{output_folder_path}/{table_name}.sql".format(output_folder_path=output_folder_path.rstrip('/'), table_name=table_name)
                if smallfile:
                    smallfile.close()
                smallfile = open(output_file_path, 'wb')
        if not table_name:
            continue
        smallfile.write(line)
    smallfile.close()

csplit(1)을 사용하여 정규 표현(테이블 경계와 일치한다고 생각됨)에 따라 출력을 개별 테이블로 잘라냅니다.

스크립트는 다음을 수행합니다.

#!/bin/sh

#edit these
USER=""
PASSWORD=""
MYSQLDIR="/path/to/backupdir"

MYSQLDUMP="/usr/bin/mysqldump"
MYSQL="/usr/bin/mysql"

echo - Dumping tables for each DB
databases=`$MYSQL --user=$USER --password=$PASSWORD -e "SHOW DATABASES;" | grep -Ev "(Database|information_schema)"`
for db in $databases; do
    echo - Creating "$db" DB
    mkdir $MYSQLDIR/$db
    chmod -R 777 $MYSQLDIR/$db
    for tb in `$MYSQL  --user=$USER --password=$PASSWORD -N -B -e "use $db ;show tables"`
        do 
            echo -- Creating table $tb
            $MYSQLDUMP --opt  --delayed-insert --insert-ignore --user=$USER --password=$PASSWORD $db $tb | bzip2 -c > $MYSQLDIR/$db/$tb.sql.bz2
    done
    echo
done

SQLDumpSplitter 2를 확인해 보십시오. 방금 40MB 덤프를 성공적으로 분할했습니다.다음 링크에서 구할 수 있습니다.

sqldumpsplitter.com

이게 도움이 됐으면 좋겠다.

bash 스크립트와 달리 Windows에서 작동하는 MySQLDumpSplitter.java를 만들었습니다.https://github.com/Verace/MySQLDumpSplitter 에서 구할 수 있습니다.

@Vérace의 답변에 대한 설명:

이클립스에서 큰 파일을 분할할 수 있는 인터랙티브 방식이 특히 마음에 듭니다.Windows에서 105GB 파일을 성공적으로 시도했습니다.

MySQLDumpSplitter 라이브러리를 프로젝트에 추가하면 됩니다.http://dl.bintray.com/verace/MySQLDumpSplitter/jar/

Import 방법에 대한 간단한 메모:

- In Eclipse, Right click on your project --> Import
- Select "File System" and then "Next"
- Browse the path of the jar file and press "Ok"
- Select (thick) the "MySQLDumpSplitter.jar" file and then "Finish"
- It will be added to your project and shown in the project folder in Package Explorer in Eclipse
- Double click on the jar file in Eclipse (in Package Explorer)
- The "MySQL Dump file splitter" window opens which you can specify the address of your dump file and proceed with split.

언급URL : https://stackoverflow.com/questions/132902/how-do-i-split-the-output-from-mysqldump-into-smaller-files

반응형