赞
踩
实现将数据库导出为sql文件(指定文件名,文件路径)
import datetime import os import subprocess # mysqldump工具所在的路径,在mysql目录下可以找到 export_cmd_path = '"C:/Program Files/MySQL/MySQL Server 8.0/bin/mysqldump"' #构建导出时文件名,这里是数据库名+此时的时间戳,数据库名根据实际名称修改 timestamp = datetime.datetime.now().strftime('%Y_%m_%d_%H_%M_%S') filename = database_name + "_" + timestamp + ".sql" # 构造cmd,下面需要根据实际情况修改: # 1. user/password为实际数据库的用户名、密码 # 2. file_path为实际备份的sql文件存储的路径 cmd = f"{export_cmd_path} -u{user} -p{password} {database_name}>{os.path.join(file_path, filename)}" # 使用subprocess模块执行 try: process = subprocess.Popen(cmd, shell=True) process.wait() if process.returncode == 0: print('export success') else: print(f'{database_name} export fail, return code:{process.returncode}') except subprocess.CalledProcessError as e: print(f'{database_name} export fail:{e}')
可以添加到windows定时任务里实现定时导出
需要新建一个数据库,假设名为new_schema,实现将dump出的sql文件import进新数据库中
import datetime import os import subprocess # mysql工具所在的路径,在mysql目录下可以找到 import_cmd_path = '"C:/Program Files/MySQL/MySQL Server 8.0/bin/mysql"' # 合成想要导入的sql file路径:file_path,database_sql_file根据实际修改 sql_file = os.path.join(file_path, database_sql_file + ".sql") cmd = f'{import_cmd_path} -u{user} -p{password} {new_schema} < {sql_file}' with open(sql_file, 'rb') as f: try: process = subprocess.Popen(cmd, shell=True, stdin=f) process.wait() if process.returncode == 0: print('import success') else: print(f'import fail, return code:{process.returncode}') except subprocess.CalledProcessError as e: print(f'import fail:{e}')
也可以直接使用mysql_workbench选择spl文件进行import
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。