python利用pymysql读取Navicat转储的sql文件并恢复数据库的数据

  • Navicat转储的sql文件的截图:
    这里写图片描述
  • python3中利用pymsql读取文件并重新恢复数据(当数据库中数据被更改后)
# -*- coding: utf-8 -*-
import pymysql


def read_sql_file(file_path):
    with open(file_path, 'r', encoding='utf8') as f:
        sql_list = []
        for line in f.readlines():
            if line.startswith('SET'):
                sql_list.append(line.replace('\n', ''))
            elif line.startswith('DROP'):
                sql_list.append(line.replace('DROP', 'TRUNCATE').replace(' IF EXISTS', '').replace('\n', ''))
            elif line.startswith('INSERT'):
                sql_list.append(line.replace('\n', ''))
            else:
                pass
    return sql_list


if __name__ == '__main__':
    path = "xxx.sql"
    connect = pymysql.connect(
        host='localhost',
        user='xxx',
        password='xxx',
        database='xxx',
        port=3306,
        charset='utf8'
    )
    cursor = connect.cursor()
    for sql in read_sql_file(path):
        cursor.execute(sql)
    connect.commit()
    cursor.close()
    connect.close()

猜你喜欢

转载自blog.csdn.net/kmlyc/article/details/80686155
今日推荐