如果不在Python中使用mysqldump,如何转储MySQL数据库

2024-04-27 05:02:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我如何在不使用mysqldump的情况下转储一个MySQL数据库,而只是使用Python包含表结构


Tags: 数据库mysql情况结构mysqldump
2条回答

我已经解决了这个问题

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()

通过一点测试,它似乎工作得很好

我建议MySQLdb——它为Python提供了一个MySQL API

但是,API很可能对mysqldump进行了间接调用。您不想直接或根本不想调用mysqldump

您可能还想查看Dump tables and data,其中显示了在不使用MySQLdb的情况下转储表结构和数据(沿页面向下)的确切过程

相关问题 更多 >