使用Python批量修改数据库执行Sql文件

由于上篇文章中批量修改了文件,有的时候数据库也需要批量修改一下,之前的做法是使用宝塔的phpMyAdmin导出一个已经修改好了的sql文件,然后依次去其他数据库里导入,效率不说极低,也算低了,且都是些重复性的劳动,所以打算用Python来批量执行sql

环境

版本:Python3.6
系统:MacOS
IDE:PyCharm
第三方库:pymysql

厦门哪里有卖厦工叉车的

Show Code

import pymysql

host = 'xxx.65.9.191'username = 'root'password = 'root'def connectMySQL():
    print('开始连接数据库')    # 打开数据库连接
    db = pymysql.connect(host,username,password,charset='utf8')    # 使用 cursor() 方法创建一个游标对象 cursor
    cursor = db.cursor()    # 使用 execute() 显示所有数据库
    cursor.execute("SHOW DATABASES")
    print('开始查询所有数据库')    # 获取所有数据库名称
    data = cursor.fetchall()    # 开始操作
    for dbb in data:
        dbname = dbb[0]
        print('选中' + dbname + '数据库')        # 选择数据库
        cursor.execute("use " + dbname)        # 查看有哪些表
        cursor.execute("show tables")
        table = cursor.fetchall()        # 如果不是3个表的就不管
        if len(table) != 3:            continue
        for tb in table:
            tbname = tb[0]
            print('开始删除'+tbname+'表')            # 删除所有的表
            cursor.execute("DROP TABLE " + tbname)
        executeScriptsFromFile('1.sql', 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()

解释代码

这是用于执行sql文件,这里第一句就有个坑,最好设置encoding='utf-8'否则可能会报错UnicodeEncodeError: 'latin-1' codec can't encode characters in position 41-44: ordinal not in range(256),当读取了sql文件后用;分割语句然后用for循环依次执行sql语句

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执行完成')

这一段比较容易理解了,首先是连接数据库,注意还是最好设置一下charset='utf8',因为我要操作多个数据库执行sql文件,所以先把数据库名称全部获取出来,这里获取出来的结果是元组类型,即使for循环后出来的也是一个元组,所以用[0]取出元组中的值,然后选中数据库执行删表操作(当然不是每个人都要按我这些操作哈,需要执行啥操作就自己改SQL语句),表删完了,然后开始执行1.sql文件,执行完成后关闭数据库

def connectMySQL():
    print('开始连接数据库')    # 打开数据库连接
    db = pymysql.connect(host,username,password,charset='utf8')    # 使用 cursor() 方法创建一个游标对象 cursor
    cursor = db.cursor()    # 使用 execute() 显示所有数据库
    cursor.execute("SHOW DATABASES")
    print('开始查询所有数据库')    # 获取所有数据库名称
    data = cursor.fetchall()    # 开始操作
    for dbb in data:
        dbname = dbb[0]
        print('选中' + dbname + '数据库')        # 选择数据库
        cursor.execute("use " + dbname)        # 查看有哪些表
        cursor.execute("show tables")
        table = cursor.fetchall()        # 如果不是3个表的就不管
        if len(table) != 3:            continue
        for tb in table:
            tbname = tb[0]
            print('开始删除'+tbname+'表')            # 删除所有的表
            cursor.execute("DROP TABLE " + tbname)
        executeScriptsFromFile('1.sql', cursor)
    db.close()

这2篇文章的代码从思路、编写、到测试,用了一下午吧!我对Python也不是很熟悉,所以中间也踩了些坑,但确实能看出来,Python作为胶水语言拿来做这些小工具真的舒服!

猜你喜欢

转载自www.cnblogs.com/xyou/p/9466251.html