#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()