简体   繁体   English

创建一个python脚本,该脚本使用mysql数据库中的结构和数据文件创建sql转储

[英]Create a python script that create a sql dump with structure and data file from mysql database

I want to make a backup script in python that make a .sql file with structure and data, and saves it on the disk? 我想在python中制作一个备份脚本,该脚本使用结构和数据制作一个.sql文件,并将其保存在磁盘上?

The issue is that i wanna make a routine for a backup remotely, so the file will be stored in a different server.. To make sure that if my server dies, the data does not die with it. 问题是我想远程创建一个备份例程,因此该文件将存储在其他服务器上。要确保服务器死机,数据也不会随之死机。

Is it possible? 可能吗?

I don't see why you want to do that in Python since there is already a command for that: mysqldump . 我不明白为什么要在Python中这样做,因为已经有一个命令: mysqldump If you specify it with: 如果使用以下命令指定它:

mysqldump -u username -p database

It will query for your password and then write the SQL statements to the stdout. 它将查询您的密码,然后将SQL语句写入标准输出。

You can use I/O redirection to write it to a file, like: 您可以使用I / O重定向将其写入文件,例如:

mysqldump -u username -p database > file.sql

Since SQL is a quite verbose language, you can also construct a zipped file, by passing the output through the gzip compressor: 由于SQL是一种非常冗长的语言,因此您还可以通过将输出传递到gzip压缩器来构造一个压缩文件:

mysqldump -u username -p database | gzip --best > file.sql.gz

If you want to "write" a program in Python that does the calls itself, you can do it with subprocess : 如果您想用Python“编写”一个程序来进行调用,可以使用subprocess

import subprocess

username = 'the_username'
password = 'the_password'
database = 'my_fancy_database'

with open('file.sql','w') as output:
    c = subprocess.Popen(['mysqldump', '-u',username,'-p%s'%password,database],
                         stdout=output, shell=True)

But this is only some logic around the mysqldump command. 但这只是围绕mysqldump命令的一些逻辑。

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

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