您的位置:首页 > 编程语言 > Python开发

Python从文件读取命令操作MySQL,并记录操作结果

2018-11-09 16:08 846 查看
[code]#encoding = utf-8

import pymysql,time,os

def log(path,s):
file_date = time.strftime("%Y-%m-%d", time.localtime())
file_time = time.strftime("%H:%M:%S", time.localtime())
try:
if os.path.exists(path):
for root,dirs,files in os.walk(path):
files_path = []
for file in files:
files_path.append(os.path.join(root,file))
if log_path+"\\"+file_date+".txt" not in files_path:
with open(path+"\\"+file_date+".txt","w") as fp:
fp.write(file_time+": "+s+"\n")
else:
with open(path+"\\"+file_date+".txt","a+") as fp:
fp.write(file_time+": "+s+"\n")
else:
os.makedirs(path)
with open(path+"\\"+file_date+".txt", "w") as fp:
fp.write(file_time+": "+s+"\n")
except Exception as e:
print("Write log fail.: "+str(e))

log_path = "F:\\python\\mysql\\log"
try:
# 创建一个连接的实例对象
conn = pymysql.connect(host="127.0.0.1",user="root",password="",database="staff",port=3306,charset="utf8")

# 创建一个可执行sql语句的对象
cur = conn.cursor()

# 执行sql语句
with open("F:\\python\\command.txt","r",encoding="utf-8") as fp:
res = ""
for line in fp:
if line.strip():    #只能除去空行,但是每行后面的换行符还是在的
res += line
# 需要将换行符删除了再判断
if line.strip("\n").endswith(";"):
cur.execute(res)
res = ""
# 捕获异常并打印
except Exception as e:
log(log_path, str(e))

# 如果创建表格和插入数据无异常,那么就执行else语句块
else:
log(log_path, "Command execute success.")

# 无论是否有异常均会执行finally语句块
finally:
conn.commit()
cur.close()
conn.close()

 

阅读更多
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐