4

I want to make a backup script in Python that make a .sql file with structure and data, and saves it on the disk.

The issue is that I want to make a routine for a remote backup, 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?

0

1 Answer 1

20

I don't see why you want to do that in Python since there is already a command for that: mysqldump [MySQL-doc]. 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.

You can use I/O redirection to write it to a file, like:

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:

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:

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Keep in mind that you are using password at the command line, and it can be captured and saved in bash_history, and viewed by other users sharing the same privilege. A better option using mysqldump may be to make it read the details from a temporary auth file.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.