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

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

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值