如何在不使用python的mysqldump的情况下转储MySQL数据库 [英] How can I dump a MySQL database without using mysqldump in Python

查看:107
本文介绍了如何在不使用python的mysqldump的情况下转储MySQL数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

仅使用包含表结构的Python,如何不使用mysqldump来转储MySQL数据库?

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

推荐答案

我已经解决了这个问题.

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.

这篇关于如何在不使用python的mysqldump的情况下转储MySQL数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆