Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I dump a MySQL database without using mysqldump in Python [closed]

Tags:

python

mysql

How can I dump a MySQL database without using mysqldump, just by using Python including table structure?

like image 206
Samuel Taylor Avatar asked May 10 '12 12:05

Samuel Taylor


People also ask

How do I dump an entire database in MySQL?

To dump/export a MySQL database, execute the following command in the Windows command prompt: mysqldump -u username -p dbname > filename. sql . After entering that command you will be prompted for your password.

Does Mysqldump lock the database?

By default, the mysqldump utility, which allows to back a MySQL database, will perform a lock on all tables until the backup is complete. In many cases, the amount of data in the database and the uptime requirements will not allow this lock in real life.

Is Mysqldump part of MySQL?

Mysqldump is part of the relational database package for MySQL. It is used to back up all the data in a database into a single text file. These files or "dumps" can be generated for individual databases or a collection of them.


1 Answers

I have solved this problem.

import MySQLdb
import os
import datetime

con = MySQLdb.connect(host='localhost', user='root', passwd='password', db='test')
cur = con.cursor()

cur.execute("SHOW TABLES")
data = ""
tables = []
for table in cur.fetchall():
    tables.append(table[0])

for table in tables:
    data += "DROP TABLE IF EXISTS `" + str(table) + "`;"

    cur.execute("SHOW CREATE TABLE `" + str(table) + "`;")
    data += "\n" + str(cur.fetchone()[1]) + ";\n\n"

    cur.execute("SELECT * FROM `" + str(table) + "`;")
    for row in cur.fetchall():
        data += "INSERT INTO `" + str(table) + "` VALUES("
        first = True
        for field in row:
            if not first:
                data += ', '
            data += '"' + str(field) + '"'
            first = False


        data += ");\n"
    data += "\n\n"

now = datetime.datetime.now()
filename = str(os.getenv("HOME")) + "/backup_" + now.strftime("%Y-%m-%d_%H:%M") + ".sql"

FILE = open(filename,"w")
FILE.writelines(data)
FILE.close()

Seem to work well from a little testing.

like image 166
Samuel Taylor Avatar answered Oct 26 '22 23:10

Samuel Taylor