Python批量执行文件夹下SQL文件

使用pymysql批量执行文件夹下SQL文件到mysql数据库中,参考文章使用Python批量修改数据库执行Sql文件

代码发布到 Gist

#!/usr/bin/env python
# -*- coding: utf-8 -*-

__author__ = "leo"
__time__ = "2018-08-01"

import os
import pymysql


def get_sql_files():
    sql_files = []
    files = os.listdir(os.path.dirname(os.path.abspath(__file__)))
    for file in files:
        if os.path.splitext(file)[1] == '.sql':
            sql_files.append(file)
    return sql_files


def connectMySQL():
    # 打开数据库连接
    db = pymysql.connect("127.0.0.1", "root", "", "hey_star", charset='utf8')

    # 使用 cursor() 方法创建一个游标对象 cursor
    cursor = db.cursor()

    for file in get_sql_files():
        executeScriptsFromFile(file, cursor)
    db.close()


def executeScriptsFromFile(filename, cursor):
    fd = open(filename, 'r', encoding='utf-8')
    sqlFile = fd.read()
    fd.close()
    sqlCommands = sqlFile.split(';')

    for command in sqlCommands:
        try:
            cursor.execute(command)
        except Exception as msg:
            print(msg)

    print('sql执行完成')


if __name__ == "__main__":
    connectMySQL()

你可能感兴趣的:(Python批量执行文件夹下SQL文件)