How can I dump a MySQL database without using mysqldump, just by using Python including table structure?
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With