如何使用 Python 一次转储一个 MySql 表

问题描述 投票:0回答:1

我在 Windows 服务器上使用 MySQL 5.6.21,需要从一台机器迁移到另一台机器。一直在尝试使用 MySQL Workbench 导出表,但在导出过程中的某个时刻,我不断收到写入错误 22。

为了简单起见,我使用 Jupyter。

我想尝试单独转储每个表,看看是哪个表导致了问题。

所以我做的第一件事就是使用一个表编写一个测试,如下所示:

import subprocess
tablename="templedger"
gettablestring="mysqldump -u user1 -pB57$52 db_main %s > G:\Databasebackup\dbmain\%s.sql" % (tablename,tablename)
subprocess.Popen(gettablestring, shell=True)
print("Done")

“完成”这个词立即出现,但没有转储

然后我尝试了以下

!{gettablestring}

并收到“访问被拒绝”

我该如何编写代码,以便可以从 Jupyter 单元中执行转储命令?

谢谢

python mysql jupyter-notebook database-backups
1个回答
0
投票

你能试试这个吗?告诉我是否有效。我在这里使用了沟通方法而不是依赖

shell=True

import subprocess

tablename = "templedger"
username = "user1"
password = "B57$52"
database = "db_main"
backup_path = "G:/Databasebackup/dbmain/"

escaped_password = password.replace("$", "\\$")
command = ["mysqldump", "-u", username, f"-p{escaped_password}", database, tablename]

with open(f"{backup_path}{tablename}.sql", "w") as output_file:
    process = subprocess.Popen(command, stdout=output_file, stderr=subprocess.PIPE)
    stdout, stderr = process.communicate()

    if process.returncode != 0:
        print(f"An error occurred: {stderr}")
    else:
        print("backup completed successfully.")
© www.soinside.com 2019 - 2024. All rights reserved.