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()
阅读更多
相关文章推荐
- Mysql 将结果保存到文件 从文件中执行sql语句 记录操作过程(tee 命令的使用)
- Mysql 将结果保存到文件 从文件里运行sql语句 记录操作过程(tee 命令的使用)
- 数据库操作_连接SQL Server数据库示例;连接ACCESS数据库;连接到 Oracle 数据库示例;SqlCommand 执行SQL命令示例;SqlDataReader 读取数据示例;使用DataAdapter填充数据到DataSet;使用DataTable存储数据库表;将数据库数据填充到 XML 文件;10 使用带输入参数的存储过程;11 使用带输入、输出参数的存储过程示;12 获得数据库中表的数目和名称;13 保存图片到SQL Server数据库示例;14 获得插入记录标识号;Exce
- 【Python】python读取文件操作mysql
- Python脚本之django---mysql-记录主机性能数据到数据库-web站点管理数据库及web显示命令执行结果
- python写的批量操作远程主机脚本(命令执行,上传、下载文件)
- Python:监控键盘输入、鼠标操作,并将捕获到的信息记录到文件中
- python 调用系统命令,并将输出重定向,输出其结果至文件或者字符串变量
- python写的批量操作远程主机脚本(命令执行,上传、下载文件)
- Python读取ini文件、操作mysql、发送邮件实例
- Python3操作MySQL,查询数据并保存到文件中
- python读取读取配置文件信息操作代码
- Python:监控键盘输入、鼠标操作,并将捕获到的信息记录到文件中
- MySql使用全记录5 -----解决Windows下用命令导入sql文件时"Failed to open file"的问题
- python文件读写操作与linux shell变量命令交互执行的方法
- python文件操作之文件读取方式
- Python os模块--路径、文件、系统命令等操作
- Linux下编程日记--目录/文件操作及返回命令结果
- python json及mysql——读取json文件存sql、数据库日期类型转换、终端操纵mysql及python codecs读取大文件问题
- mysql的历史命令记录,~/.mysql_history,指定该文件路径