简体   繁体   English

如何使用 Python 恢复 MySQL 数据库

[英]How to restore MySQL database using Python

I have a sql file generated during database backup process and I want to load all database content from that sql file to a different MySQL database (secondary database).我在数据库备份过程中生成了一个 sql 文件,我想将该 sql 文件中的所有数据库内容加载到不同的 MySQL 数据库(辅助数据库)。

I have created a python function to load the whole database in that sql file but when I execute the function, I get an error我创建了一个 python 函数来将整个数据库加载到该 sql 文件中,但是当我执行该函数时,出现错误

'str' object is not callable 'str' 对象不可调用

Below is python script下面是python脚本

def load_database_dump_to_secondary_mysql(file_path='db_backup_file.sql'):
        query = f'source {file_path}'
        try:
            connection = mysql_hook.get_conn() # connection to secondary db
            cursor = connection.cursor(query)
            print('LOAD TO MYSQL COMPLETE')
        except Exception as xerror:
            print("LOAD ERROR: ", xerror)

NB: mysql_hook is an airflow connector that contains MySQL DB connection info such as Host, user/passwd, Database name.注意:mysql_hook 是一个气流连接器,其中包含 MySQL 数据库连接信息,例如主机、用户/密码、数据库名称。 Also, I don't have connection to the primary database, I'm only receiving sql dump file.另外,我没有连接到主数据库,我只接收 sql 转储文件。

What I'm I missing?我错过了什么?

source is a client builtin command: https://dev.mysql.com/doc/refman/8.0/en/mysql-commands.html source是一个客户端内置命令: https ://dev.mysql.com/doc/refman/8.0/en/mysql-commands.html

It's not an SQL query that MySQL's SQL parser understands.它不是 MySQL 的 SQL 解析器能够理解的 SQL 查询。

So you can't execute source using cursor.execute() , because that goes directly to the dynamic SQL interface.所以你不能使用cursor.execute()执行source ,因为它直接进入动态 SQL 接口。

You must run it using the MySQL command-line client as a subprocess:您必须使用 MySQL 命令行客户端作为子进程运行它:

subprocess.run(['mysql', '-e', f'source {file_path}'])

You might need other options to the mysql client, such as user, password, host, etc.您可能需要 mysql 客户端的其他选项,例如用户、密码、主机等。

try this尝试这个

import mysql.connector as m

# database which you want to backup
db = 'geeksforgeeks'

connection = m.connect(host='localhost', user='root',
                    password='123', database=db)
cursor = connection.cursor()

# Getting all the table names
cursor.execute('SHOW TABLES;')
table_names = []
for record in cursor.fetchall():
    table_names.append(record[0])

backup_dbname = db + '_backup'
try:
    cursor.execute(f'CREATE DATABASE {backup_dbname}')
except:
    pass

cursor.execute(f'USE {backup_dbname}')

for table_name in table_names:
    cursor.execute(
        f'CREATE TABLE {table_name} SELECT * FROM {db}.{table_name}')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM