批量还原sql文件

需求:单位里的睿智不会批量还原sql文件,这些文件在同一个数据库,单表的数据量不算大
解决:批量读取文件,然后运行sql语句就可以了,此方法适用于MySQL数据库

# -*- coding: utf-8 -*-
# @Time    : 2018/8/8 22:14
# @Author  : xiangchaoming
# @QQ      : 239036082

import os, subprocess
import pymysql
import pymysql.cursors


def create_sql():
    sql_list = []
    for root, dirs, files in os.walk("D:/temp"):
        for file in files:
            if file.endswith("sql"):
                file_path = os.path.join(root, file)
                sql_list.append(file_path)
    return sql_list


def mysql_handle():
    db = pymysql.connect(host="192.168.11.117", user="root",
                         password="", db="xiang", port=3306)

    # 使用cursor()方法获取操作游标
    cur = db.cursor()


    try:
        for sql_path in create_sql():
            try:
                with open(sql_path, "r", encoding="utf-8") as f:
                    sqls = f.read().replace("<--db-prefix-->", "").split(";\n")
                    ##执行sql语句,使用循环执行sql语句
                for sql in sqls:
                    print(sql)
                    if sql.__contains__("CREATE DATABASE `") or sql.__contains__("USE `"):
                        pass
                    else:
                        cur.execute(sql+";")
            except Exception as e:
                print(e)
                pass

    except Exception as e:
        print(e)
        pass
        # 错误回滚
        # db.rollback()
    finally:
        cur.close()
        db.commit()
        db.close()


if __name__=="__main__":
    mysql_handle()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值