利用Python如何批量修改数据库执行Sql文件
前言
由于上篇文章中批量修改了文件,有的时候数据库也需要批量修改一下,之前的做法是使用宝塔的phpMyAdmin导出一个已经修改好了的sql文件,然后依次去其他数据库里导入,效率不说极低,也算低了,且都是些重复性的劳动,所以打算用Python来批量执行sql
环境
- 版本:Python3.6
- 系统:MacOS
- IDE:PyCharm
- 第三方库:pymysql
ShowCode
importpymysql
host='xxx.65.9.191'
username='root'
password='root'
defconnectMySQL():
print('开始连接数据库')
#打开数据库连接
db=pymysql.connect(host,username,password,charset='utf8')
#使用cursor()方法创建一个游标对象cursor
cursor=db.cursor()
#使用execute()显示所有数据库
cursor.execute("SHOWDATABASES")
print('开始查询所有数据库')
#获取所有数据库名称
data=cursor.fetchall()
#开始操作
fordbbindata:
dbname=dbb[0]
print('选中'+dbname+'数据库')
#选择数据库
cursor.execute("use"+dbname)
#查看有哪些表
cursor.execute("showtables")
table=cursor.fetchall()
#如果不是3个表的就不管
iflen(table)!=3:
continue
fortbintable:
tbname=tb[0]
print('开始删除'+tbname+'表')
#删除所有的表
cursor.execute("DROPTABLE"+tbname)
executeScriptsFromFile('1.sql',cursor)
db.close()
defexecuteScriptsFromFile(filename,cursor):
fd=open(filename,'r',encoding='utf-8')
sqlFile=fd.read()
fd.close()
sqlCommands=sqlFile.split(';')
forcommandinsqlCommands:
try:
cursor.execute(command)
exceptExceptionasmsg:
print(msg)
print('sql执行完成')
if__name__=="__main__":
connectMySQL()
解释代码
这是用于执行sql文件,这里第一句就有个坑,最好设置encoding='utf-8'否则可能会报错UnicodeEncodeError:'latin-1'codeccan'tencodecharactersinposition41-44:ordinalnotinrange(256),当读取了sql文件后用;分割语句然后用for循环依次执行sql语句
defexecuteScriptsFromFile(filename,cursor):
fd=open(filename,'r',encoding='utf-8')
sqlFile=fd.read()
fd.close()
sqlCommands=sqlFile.split(';')
forcommandinsqlCommands:
try:
cursor.execute(command)
exceptExceptionasmsg:
print(msg)
print('sql执行完成')
这一段比较容易理解了,首先是连接数据库,注意还是最好设置一下charset='utf8',因为我要操作多个数据库执行sql文件,所以先把数据库名称全部获取出来,这里获取出来的结果是元组类型,即使for循环后出来的也是一个元组,所以用[0]取出元组中的值,然后选中数据库执行删表操作(当然不是每个人都要按我这些操作哈,需要执行啥操作就自己改SQL语句),表删完了,然后开始执行1.sql文件,执行完成后关闭数据库
defconnectMySQL():
print('开始连接数据库')
#打开数据库连接
db=pymysql.connect(host,username,password,charset='utf8')
#使用cursor()方法创建一个游标对象cursor
cursor=db.cursor()
#使用execute()显示所有数据库
cursor.execute("SHOWDATABASES")
print('开始查询所有数据库')
#获取所有数据库名称
data=cursor.fetchall()
#开始操作
fordbbindata:
dbname=dbb[0]
print('选中'+dbname+'数据库')
#选择数据库
cursor.execute("use"+dbname)
#查看有哪些表
cursor.execute("showtables")
table=cursor.fetchall()
#如果不是3个表的就不管
iflen(table)!=3:
continue
fortbintable:
tbname=tb[0]
print('开始删除'+tbname+'表')
#删除所有的表
cursor.execute("DROPTABLE"+tbname)
executeScriptsFromFile('1.sql',cursor)
db.close()
这2篇文章的代码从思路、编写、到测试,用了一下午吧!我对Python也不是很熟悉,所以中间也踩了些坑,但确实能看出来,Python作为胶水语言拿来做这些小工具真的舒服!
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对毛票票的支持。