使用Python3导出MySQL查询数据
整理个Python3导出MySQL查询数据d的脚本。
Python依赖包:
pymysql
xlwt
Python脚本:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# =============================================================================
# FileName:
# Desc:
# Author:
# Email:
# HomePage:
# Version:
# LastChange:
# History:
# =============================================================================
import pymysql
import traceback
import logging
import xlwt
import datetime logger = logging.getLogger(__name__) class MySQLServer(object):
def __init__(self, mysql_host,
mysql_user,
mysql_password,
mysql_port=3306,
database_name="mysql",
mysql_charset="utf8",
connect_timeout=60):
self.mysql_host = mysql_host
self.mysql_user = mysql_user
self.mysql_password = mysql_password
self.mysql_port = mysql_port
self.connect_timeout = connect_timeout
self.mysql_charset = mysql_charset
self.database_name = database_name def get_connection(self, return_dict=False):
"""
获取当前服务器的MySQL连接
:return:
"""
if return_dict:
conn = pymysql.connect(
host=self.mysql_host,
user=self.mysql_user,
passwd=self.mysql_password,
port=self.mysql_port,
connect_timeout=self.connect_timeout,
charset=self.mysql_charset,
db=self.database_name,
cursorclass=pymysql.cursors.DictCursor
)
else:
conn = pymysql.connect(
host=self.mysql_host,
user=self.mysql_user,
passwd=self.mysql_password,
port=self.mysql_port,
connect_timeout=self.connect_timeout,
charset=self.mysql_charset,
db=self.database_name,
cursorclass=pymysql.cursors.Cursor
) return conn def mysql_exec(self, mysql_script, mysql_paras=None):
conn = None
cursor = None
try:
message = "在服务器{0}上执行脚本:{1},参数为:{2}".format(
self.mysql_host, mysql_script, str(mysql_paras))
logger.debug(message)
conn = self.get_connection()
cursor = conn.cursor()
if mysql_paras is not None:
cursor.execute(mysql_script, mysql_paras)
else:
cursor.execute(mysql_script)
conn.commit()
except Exception as ex:
warning_message = """
execute script:{mysql_script}
execute paras:{mysql_paras},
execute exception:{mysql_exception}
execute traceback:{mysql_traceback}
""".format(
mysql_script=mysql_script,
mysql_paras=str(mysql_paras),
mysql_exception=str(ex),
mysql_traceback=traceback.format_exc()
)
logger.warning(warning_message)
raise Exception(str(ex))
finally:
if cursor is not None:
cursor.close()
if conn is not None:
conn.close() def mysql_exec_many(self, script_items):
conn = None
cursor = None
try:
conn = self.get_connection()
cursor = conn.cursor()
for script_item in script_items:
sql_script, sql_paras = script_item
message = "在服务器{0}上执行脚本:{1},参数为:{2}".format(
self.mysql_host, sql_script, str(sql_paras))
logger.debug(message)
if sql_paras is not None:
cursor.execute(sql_script, sql_paras)
else:
cursor.execute(sql_script)
conn.commit()
except Exception as ex:
logger.warning("execute exception:{0} \n {1}".format(str(ex), traceback.format_exc()))
raise Exception(str(ex))
finally:
if cursor is not None:
cursor.close()
if conn is not None:
conn.close() def mysql_query(self, mysql_script, mysql_paras=None, return_dict=False):
conn = None
cursor = None
try:
message = "在服务器{0}上执行脚本:{1},参数为:{2}".format(
self.mysql_host, mysql_script, str(mysql_paras))
logger.debug(message)
conn = self.get_connection(return_dict=return_dict)
cursor = conn.cursor()
if mysql_paras is not None:
cursor.execute(mysql_script, mysql_paras)
else:
cursor.execute(mysql_script)
exec_result = cursor.fetchall()
conn.commit()
return exec_result
except Exception as ex:
warning_message = """
execute script:{mysql_script}
execute paras:{mysql_paras},
execute exception:{mysql_exception}
execute traceback:{mysql_traceback}
""".format(
mysql_script=mysql_script,
mysql_paras=str(mysql_paras),
mysql_exception=str(ex),
mysql_traceback=traceback.format_exc()
)
logger.warning(warning_message)
raise Exception(str(ex))
finally:
if cursor is not None:
cursor.close()
if conn is not None:
conn.close() class ExeclExporter(object):
@classmethod
def export_excel(cls, file_path, row_items):
try:
work_book = xlwt.Workbook()
work_sheet = work_book.add_sheet('sheet01', cell_overwrite_ok=True)
column_items = []
if len(row_items) > 0:
first_row = row_items[0]
column_items = list(first_row.keys())
for column_index in range(0, len(column_items)):
column_name = column_items[column_index]
work_sheet.write(0, column_index, column_name)
for row_index in range(1, len(row_items) + 1):
row_item = row_items[row_index - 1]
for column_index in range(0, len(column_items)):
column_name = column_items[column_index]
work_sheet.write(row_index, column_index, row_item[column_name])
work_book.save(file_path)
except Exception as ex:
logger.warning("执行异常,异常信息:{0}\n堆栈信息:{1}".format(
str(ex),
traceback.format_exc()
)) def export_excel():
mysql_server = MySQLServer(
mysql_host="192.168.199.194",
mysql_port=3306,
mysql_user='admin',
mysql_password='admin',
database_name='demo01',
mysql_charset='utf8'
)
sql_script = """
select * from tb001 limit 10;
"""
row_items = mysql_server.mysql_query(mysql_script=sql_script, return_dict=True)
file_path = "./" + datetime.datetime.now().strftime("%Y%m%d%H%M%S.xls")
ExeclExporter.export_excel(
file_path=file_path,
row_items=row_items) if __name__ == '__main__':
export_excel()
使用Python3导出MySQL查询数据的更多相关文章
- mysql 查询数据时按照A-Z顺序排序返回结果集
mysql 查询数据时按照A-Z顺序排序返回结果集 $sql = "SELECT * , ELT( INTERVAL( CONV( HEX( left( name, 1 ) ) , 16, ...
- MySQL 查询数据
MySQL 查询数据 MySQL 数据库使用SQL SELECT语句来查询数据. 你可以通过 mysql> 命令提示窗口中在数据库中查询数据,或者通过PHP脚本来查询数据. 语法 以下为在MyS ...
- MySQL查询数据表中数据记录(包括多表查询)
MySQL查询数据表中数据记录(包括多表查询) 在MySQL中创建数据库的目的是为了使用其中的数据. 使用select查询语句可以从数据库中把数据查询出来. select语句的语法格式如下: sele ...
- 十二、MySQL 查询数据
MySQL 查询数据 MySQL 数据库使用SQL SELECT语句来查询数据. 你可以通过 mysql> 命令提示窗口中在数据库中查询数据,或者通过PHP脚本来查询数据. 语法 以下为在MyS ...
- navicat for Mysql查询数据不能直接修改
navicat for Mysql查询数据不能直接修改 原来的sql语句: <pre> select id,name,title from table where id = 5;</ ...
- php MySQL 查询数据
以下为在MySQL数据库中查询数据通用的 SELECT 语法: SELECT column_name,column_name FROM table_name [WHERE Clause] [LIMIT ...
- 吴裕雄--天生自然MySQL学习笔记:MySQL 查询数据
MySQL 数据库使用SQL SELECT语句来查询数据. 可以通过 mysql> 命令提示窗口中在数据库中查询数据,或者通过PHP脚本来查询数据. 语法 以下为在MySQL数据库中查询数据通用 ...
- 使用Connector / Python连接MySQL/查询数据
使用Connector / Python连接MySQL connect()构造函数创建到MySQL服务器的连接并返回一个 MySQLConnection对象 在python中有以下几种方法可以连接到M ...
- 导出mysql内数据 python建倒排索引
根据mysql内数据,python建倒排索引,再导回mysql内. 先把mysql内的数据导出,先导出为csv文件,因为有中文,直接打开csv文件会乱码,再直接改文件的后缀为txt,这样打开时不会是乱 ...
随机推荐
- [LeetCode] 660. Remove 9 移除9
Start from integer 1, remove any integer that contains 9 such as 9, 19, 29... So now, you will have ...
- [LeetCode] 75. Sort Colors 颜色排序
Given an array with n objects colored red, white or blue, sort them in-place so that objects of the ...
- thinkphp5.1 - twig模板-全局变量
thinkphp5.1 - twig模板-全局变量我们在定义 ccs 之类的静态文件的时候,经常会使用<link rel="stylesheet" href="__ ...
- .NET Core:Json和XML
(1)Json WebAPI默认使用Json格式,如果需要更改默认的Json设置在Startup的ConfigureServices方法中修改:services.AddMvc() .AddJsonOp ...
- 深入理解C语言 - 指针使用的常见错误
在C语言中,指针的重要性不言而喻,但在很多时候指针又被认为是一把双刃剑.一方面,指针是构建数据结构和操作内存的精确而高效的工具.另一方面,它们又很容易误用,从而产生不可预知的软件bug.下面总结一下指 ...
- Unity和Jenkins真是绝配,将打包彻底一键化!
说起打包,我们的QA简直是要抓狂,这个确实我也很同情他们.项目最开始打包是另一个同事做的,打包步骤是有些繁琐,但是项目上线后,不敢轻易动啊!每次他们打包总要跟我抱怨,国内版本打包步骤要10多步还能忍, ...
- mysql获取日期语句汇总
汇总一些MySQL获取日期的SQL语句. -- 今天 SELECT DATE_FORMAT(NOW(),'%Y-%m-%d 00:00:00') AS '今天开始'; SELECT DATE_FORM ...
- logstash之mongodb-log
1.logstash6.5.3 配置收集mongodb的日志: 首先在mongodb服务器上部署filebeat收集日志并上传到logstash进行处理,然后上传到ES. filebeat-conf: ...
- python--unittest测试框架
unittest中最核心的四个概念是:test case, test suite, test runner, test fixture
- 补习系列(12)-springboot 与邮件发送【华为云技术分享】
目录 一.邮件协议 关于数据传输 二.SpringBoot 与邮件 A. 添加依赖 B. 配置文件 C. 发送文本邮件 D.发送附件 E. 发送Html邮件 三.CID与图片 参考文档 一.邮件协议 ...