一、图解流程:(转)
二、代码部分
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author:suhan
#time:2020-06-09
import pymysql.cursors,sys,time
# sql执行函数。传入连接,游标,sql文件
def sqlExecuteFromFile (connect,cursor,SqlFile):
# 记录成功和失败的语句
fileTime = time.strftime("%Y-%m-%d", time.localtime())
RetLog = "result" + fileTime + ".log"
#打开sql语句的文件并一条条执行
with open(SqlFile,'r',encoding='utf-8') as f:
#记录成功执行的语句到文件中
with open(RetLog, 'a+', encoding='utf-8') as fs:
for SqlLine in f:
execTime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
try:
# 执行和记录
cursor.execute(SqlLine)
# 提交。执行一次提交一次。大量变更时只做一次提交,防止提交超时,失败。
connect.commit()
Ret = execTime + "##success##" + SqlLine
fs.write(Ret)
# 错误的分类应该跟细一些,分为数据库执行错误和写文件错误;
# commit成功了,写日志失败的情况,重新记录了已经成功的sql认为是失败的。
except Exception as e:
#如果有失败就回滚并记录
connect.rollback()
#写的错误日志记录。
ErrorMessage = "Error {0}".format(str(e))
Ret = execTime + "##failure##" + ErrorMessage + "##" + SqlLine
fs.write(Ret)
# 关闭游标
cursor.close()
if __name__ == "__main__" :
# 判断输入参数个数。0是py文件名,1表示第一个输入参数。
if len(sys.argv) != 2:
print("请输入sql文件的路径。")
sys.exit(0)
# sql文件名。
SqlFile = sys.argv[1]
# 连接数据库,port不能带引号
connect = pymysql.connect(
host='127.0.0.1',
port=3306,
user='root',
passwd='8491510',
db='suhantest'
)
try :
# 获取游标
cursor = connect.cursor()
except Exception as ee:
print("连接数据库失败")
print("-------连接数据库成功,开始执行sql-------")
# 读取文件执行sql
sqlExecuteFromFile(connect,cursor,SqlFile)
# # 执行查询的语句样例,留存。
# effect_row = cursor.execute("select * from product_channel")
# # 打印一条
# print(cursor.fetchone())
#关闭连接
connect.close()
print('sql全部执行完,查看resultxx.log确认是否有问题。')
三、参考
https://www.cnblogs.com/1832921tongjieducn/p/11128951.html
https://blog.csdn.net/guofeng93/article/details/53994112