分享

Python学习教程:使用Python批量修改数据库执行Sql文件

 千锋Python学堂 2019-08-20

这篇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()

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多