Backing up a database with Python

As we have seen, there are three methods of archiving a MySQL database that a developer can use:

  • Copying the MySQL table files directly
  • Exporting data to a delimited text file
  • Creating a dumpfile

The first and last of these require special permissions on the server. To use Python to manage the backup merely automates the process but still requires you to have access beyond SELECT.

Using MySQLdb, however, we can export the data with only basic privileges. Simply store the results of the SELECT statement into a variable, format it appropriately, and write it to a file.

Get MySQL for Python now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.