使用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,这样打开时不会是乱 ...
随机推荐
- ACE网络编程:IPC SAP、ACE_SOCKET和TCP/IP通信实例
socket.TLI.STREAM管道和FIFO为访问局部和全局IPC机制提供广泛的接口.但是,有许多问题与这些不统一的接口有关联.比如类型安全的缺乏和多维度的复杂性会导致成问题的和易错的编程.ACE ...
- A1067 Sort with Swap(0, i) (25 分)
一.技术总结 题目要求是,只能使用0,进行交换位置,然后达到按序排列,所使用的最少交换次数 输入时,用数组记录好每个数字所在的位置. 然后使用for循环,查看i当前位置是否为该数字,核心是等待0回到自 ...
- [LeetCode] 81. Search in Rotated Sorted Array II 在旋转有序数组中搜索之二
Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. (i.e. ...
- 远程文件传输命令•RHEL8/CentOS8文件上传下载-用例
scp协议 scp [options] [本地用户名@IP地址:]file1 [远程用户名 @IP 地址 :] file2 options: -v 用来显示进度,可以用来查看连接,认证,或是配置错误. ...
- springcloud(七,多个服务消费者配置,以及zuul网关案例)
spring cloud (一.服务注册demo_eureka) spring cloud (二.服务注册安全demo_eureka) spring cloud (三.服务提供者demo_provid ...
- 通过Windows实现端口转发
转自:月光博客<通过Windows实现端口转发> 这里介绍一个使用两台云服务器访问外网的方法,一台国内服务器,一台国外服务器,国内服务器通过端口转发来用于中转,中转的好处是,服务器对服务器 ...
- Docker remote API
Docker remote API 该教程基于Ubuntu或Debian环境,如果不是,请略过本文 Docker API 在Docker生态系统中一共有三种API Registry API:提供了与来 ...
- microbit之mpython的API
附录:常用API函数汇总 一.显示 display.scroll("Hello, World!") 在micro:bit点阵上滚动显示Hello, World!,其中Hello, ...
- 如何解决aws解绑银行卡问题?
首先先来说明一下我自己的情况? 一年的免费使用 前提:没有开启任何的实例服务 先贴一条官方的解释 关于我小白一个.学校课程要求使用aws,注册之后在网络上看到一堆人踩坑,aws的扣费就是个坑! 预授权 ...
- [JAVA] 日常填坑 java.lang.SecurityException: Prohibited package name: java.xxx
java虚拟机不允许包名以java开头. https://blog.csdn.net/sinat_28690417/article/details/72328547