简体   繁体   English

从命令行将 mysql 数据库转储到明文 (CSV) 备份

[英]Dump a mysql database to a plaintext (CSV) backup from the command line

I'd like to avoid mysqldump since that outputs in a form that is only convenient for mysql to read.我想避免使用 mysqldump,因为它以一种仅便于 mysql 阅读的形式输出。 CSV seems more universal (one file per table is fine). CSV 似乎更通用(每个表一个文件就可以)。 But if there are advantages to mysqldump, I'm all ears.但如果 mysqldump 有优势,我会洗耳恭听。 Also, I'd like something I can run from the command line (linux).另外,我想要一些可以从命令行 (linux) 运行的东西。 If that's a mysql script, pointers to how to make such a thing would be helpful.如果那是一个 mysql 脚本,那么指向如何制作这样的东西的指针会很有帮助。

If you can cope with table-at-a-time, and your data is not binary, use the -B option to the mysql command.如果您可以处理一次表,并且您的数据不是二进制的,请使用mysql命令的-B选项。 With this option it'll generate TSV (tab separated) files which can import into Excel, etc, quite easily:使用此选项,它将生成可以很容易地导入 Excel 等的 TSV(制表符分隔)文件:

% echo 'SELECT * FROM table' | mysql -B -uxxx -pyyy database

Alternatively, if you've got direct access to the server's file system, use SELECT INTO OUTFILE which can generate real CSV files:或者,如果您可以直接访问服务器的文件系统,请使用SELECT INTO OUTFILE它可以生成真正的 CSV 文件:

SELECT * INTO OUTFILE 'table.csv'
    FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'
    LINES TERMINATED BY '\n'
FROM table

In MySQL itself, you can specify CSV output like:在 MySQL 本身中,您可以指定 CSV 输出,如:

SELECT order_id,product_name,qty
FROM orders
INTO OUTFILE '/tmp/orders.csv'
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
LINES TERMINATED BY '\n'

From http://www.tech-recipes.com/rx/1475/save-mysql-query-results-into-a-text-or-csv-file/来自http://www.tech-recipes.com/rx/1475/save-mysql-query-results-into-a-text-or-csv-file/

You can dump a whole database in one go with mysqldump's --tab option.您可以使用mysqldump's --tab选项一次性转储整个数据库。 You supply a directory path and it creates one .sql file with the CREATE TABLE DROP IF EXISTS syntax and a .txt file with the contents, tab separated.您提供一个目录路径,它会使用CREATE TABLE DROP IF EXISTS语法创建一个.sql文件和一个包含内容的.txt文件,制表符分隔。 To create comma separated files you could use the following:要创建逗号分隔的文件,您可以使用以下内容:

mysqldump --password  --fields-optionally-enclosed-by='"' --fields-terminated-by=',' --tab /tmp/path_to_dump/ database_name

That path needs to be writable by both the mysql user and the user running the command, so for simplicity I recommend chmod 777 /tmp/path_to_dump/ first.该路径需要 mysql 用户和运行命令的用户都可以写,所以为了简单起见,我首先推荐chmod 777 /tmp/path_to_dump/

select into outfile 选项对我不起作用,但下面通过 SED 管道制表符分隔文件的迂回方式做到了:

mysql -uusername -ppassword -e "SELECT * from tablename" dbname | sed 's/\t/","/g;s/^/"/;s/$/"/' > /path/to/file/filename.csv

Here is the simplest command for it这是最简单的命令

mysql -h<hostname> -u<username> -p<password> -e 'select * from databaseName.tableNaame' | sed  's/\t/,/g' > output.csv

If there is a comma in the column value then we can generate .tsv instead of .csv with the following command如果列值中有逗号,那么我们可以使用以下命令生成 .tsv 而不是 .csv

mysql -h<hostname> -u<username> -p<password> -e 'select * from databaseName.tableNaame' > output.csv

You can use below script to get the output to csv files.您可以使用以下脚本将输出获取到 csv 文件。 One file per table with headers.每个表一个文件,带有标题。

for tn in `mysql --batch --skip-page --skip-column-name --raw -uuser -ppassword -e"show tables from mydb"`
do 
mysql -uuser -ppassword mydb -B -e "select * from \`$tn\`;" | sed 's/\t/","/g;s/^/"/;s/$/"/;s/\n//g' > $tn.csv
done

user is your user name, password is the password if you don't want to keep typing the password for each table and mydb is the database name. user 是您的用户名,password 是密码,如果您不想继续为每个表键入密码,而 mydb 是数据库名称。

Explanation of the script: The first expression in sed, will replace the tabs with "," so you have fields enclosed in double quotes and separated by commas.脚本说明: sed 中的第一个表达式将用“,”替换制表符,因此您的字段用双引号括起来并用逗号分隔。 The second one insert double quote in the beginning and the third one insert double quote at the end.第二个在开头插入双引号,第三个在结尾插入双引号。 And the final one takes care of the \\n.最后一个处理\\n。

If you really need a "Backup" then you also need database schema, like table definitions, view definitions, store procedures and so on.如果您真的需要“备份”,那么您还需要数据库模式,如表定义、视图定义、存储过程等。 A backup of a database isn't just the data.数据库的备份不仅仅是数据。

The value of the mysqldump format for backup is specifically that it is very EASY to use it to restore mysql databases.用于备份的mysqldump格式的价值在于它非常容易使用它来恢复mysql数据库。 A backup that isn't easily restored is far less useful.不容易恢复的备份就没那么有用了。 If you are looking for a method to reliably backup mysql data to so you can restore to a mysql server then I think you should stick with the mysqldump tool.如果您正在寻找一种方法来可靠地备份 mysql 数据,以便您可以恢复到 mysql 服务器,那么我认为您应该坚持使用 mysqldump 工具。

Mysql is free and runs on many different platforms. Mysql 是免费的,可以在许多不同的平台上运行。 Setting up a new mysql server that I can restore to is simple.设置一个我可以恢复到的新 mysql 服务器很简单。 I am not at all worried about not being able to setup mysql so I can do a restore.我一点也不担心无法设置 mysql 以便我可以进行恢复。

I would be far more worried about a custom backup/restore based on a fragile format like csv/tsv failing.我会更担心基于像 csv/tsv 这样的脆弱格式的自定义备份/恢复失败。 Are you sure that all your quotes, commas, or tabs that are in your data would get escaped correctly and then parsed correctly by your restore tool?您确定数据中的所有引号、逗号或制表符都会被正确转义,然后被还原工具正确解析吗?

If you are looking for a method to extract the data then see several in the other answers.如果您正在寻找一种提取数据的方法,请查看其他答案中的几个。

Check out mk-parallel-dump which is part of the ever-useful maatkit suite of tools .查看mk-parallel-dump ,它是非常有用的maatkit 工具套件的一部分 This can dump comma-separated files with the --csv option.这可以使用 --csv 选项转储逗号分隔的文件。

This can do your whole db without specifying individual tables, and you can specify groups of tables in a backupset table.这可以在不指定单个表的情况下完成整个数据库,并且您可以在备份集表中指定表组。

Note that it also dumps table definitions, views and triggers into separate files.请注意,它还会将表定义、视图和触发器转储到单独的文件中。 In addition providing a complete backup in a more universally accessible form, it also immediately restorable with mk-parallel-restore除了以更普遍可访问的形式提供完整备份之外,它还可以立即使用mk-parallel-restore 进行恢复

If you want to dump the entire db as csv如果要将整个数据库转储为 csv

#!/bin/bash

host=hostname
uname=username
pass=password

port=portnr
db=db_name
s3_url=s3://buckera/db_dump/



DATE=`date +%Y%m%d`
rm -rf $DATE

echo 'show tables' | mysql -B -h${host} -u${uname} -p${pass} -P${port} ${db} > tables.txt
awk 'NR>1' tables.txt > tables_new.txt

while IFS= read -r line
do
  mkdir -p $DATE/$line
  echo "select * from $line" | mysql -B -h"${host}" -u"${uname}" -p"${pass}" -P"${port}" "${db}" > $DATE/$line/dump.tsv
done < tables_new.txt

touch $DATE/$DATE.fin


rm -rf tables_new.txt tables.txt

Two line PowerShell answer:两行 PowerShell 答案:

# Store in variable
$Global:csv = (mysql -uroot -p -hlocalhost -Ddatabase_name -B -e "SELECT * FROM some_table") `
| ConvertFrom-Csv -Delimiter "`t"

# Out to csv
$Global:csv | Export-Csv "C:\temp\file.csv" -NoTypeInformation

Boom-bata-boom砰砰砰

-D = the name of your database -D = 数据库名称

-e = query -e = 查询

-B = tab-delimited -B = 制表符分隔

There's a slightly simpler way to get all the tables into tab delimited fast:有一种稍微简单的方法可以快速将所有表格放入制表符分隔中:

#!/bin/bash
tablenames=$(mysql your_database -e "show tables;" -B |sed "1d")

IFS=$'\n'

tables=($tablenames)

for table in ${tables[@]}; do
        mysql your_database -e "select * from ${table}" -B > "${table}.tsv"
done

Here's a basic python script that does the work.这是完成工作的基本 python 脚本。 You can also choose to export only the headers (column names) or headers & data both.您还可以选择仅导出标题(列名)或同时导出标题和数据。

Just change the database credentials and run the script.只需更改数据库凭据并运行脚本即可。 It will output all the data to the output folder.它将output的所有数据放到output文件夹中。

To run the script -运行脚本 -

  1. Run: pip install mysql-connector-python运行:pip 安装 mysql-connector-python
  2. Change database credentials in the "INPUT" section在“INPUT”部分更改数据库凭据
  3. Run: python filename.py运行:python 文件名.py
import mysql.connector
from pathlib import Path
import csv 

#========INPUT===========
databaseHost=""
databaseUsername=""
databasePassword=""
databaseName=""
outputDirectory="./WITH-DATA/"
exportTableData=True #MAKING THIS FIELD FALSE WILL STORE ONLY THE TABLE HEADERS (COLUMN NAMES) IN THE CSV FILE
#========INPUT END===========


Path(outputDirectory).mkdir(parents=True, exist_ok=True)

mydb = mysql.connector.connect(
  host=databaseHost,
  user=databaseUsername,
  password=databasePassword
)
mycursor = mydb.cursor()
mycursor.execute("USE "+databaseName)


mycursor.execute("SHOW TABLES")
tables = mycursor.fetchall()  

tableNames=[table[0] for table in tables]

print("================================")
print("Total number of tables: "+ str(len(tableNames)))
print(tableNames)
print("================================")

for tableName in tableNames:

    print("================================")
    print("Processing: "+ str(tableName))

    mydb = mysql.connector.connect(
        host=databaseHost,
        user=databaseUsername,
        password=databasePassword
    )
    mycursor = mydb.cursor()
    mycursor.execute("USE "+databaseName)

    if exportTableData:
        mycursor.execute("SELECT * FROM "+tableName)
    else:
        mycursor.execute("SELECT * FROM "+tableName+" LIMIT 1")

    print(mycursor.column_names)

    with open(outputDirectory+tableName+".csv", 'w', newline='') as csvfile: 
        csvwriter = csv.writer(csvfile) 

        csvwriter.writerow(mycursor.column_names) 

        if exportTableData:
            myresult = mycursor.fetchall()
            csvwriter.writerows(myresult)

输出文件夹

每个表的 CSV 文件

CSV 中的数据

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM