使用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,这样打开时不会是乱 ...
随机推荐
- zzDeep Learning Papers Translation(CV)
Deep Learning Papers Translation(CV) Image Classification AlexNetImageNet Classification with Deep C ...
- 爬虫-js
js的RSA加密 var encrypt = new JSEncrypt(); encrypt.setPublicKey(publickey); # publickey是已知的 encrypt.en ...
- [RN] React Native 错误 Module does not exist in the module map
React Native 错误 Module does not exist in the module map 代码如下: import Login from 'login' import Index ...
- 【转】用C语言实现FFT算法
傅里叶变换 快速傅里叶变换(Fast Fourier Transform,FFT)是一种可在 时间内完成的离散傅里叶变换(Discrete Fourier transform,DFT)算法. 在算法 ...
- Linux性能优化实战学习笔记:第五十二讲
一.上节回顾 上一节,我们一起学习了怎么使用动态追踪来观察应用程序和内核的行为.先简单来回顾一下.所谓动态追踪,就是在系统或者应用程序还在正常运行的时候,通过内核中提供的探针,来动态追踪它们的行为,从 ...
- 【领会要领】web前端-轻量级框架应用(jQuery基础)
作者 | Jeskson 来源 | 达达前端小酒馆 jquery的安装和语法,jquery的多种选择器,dom操作和jquery事件. jQuery框架,简介,优势,安装,语法,jQuery选择器,i ...
- Linux中Too many open files 问题分析和解决
今天某个服务的日志中出现了大量的异常: [WARN ] 2018-06-15 16:55:20,831 --New I/O server boss #1 ([id: 0x55007b59, /0.0. ...
- React Hooks 深入系列
本文基于近段时间对 hooks 碎片化的理解作一次简单梳理, 个人博客.同时欢迎关注基于 hooks 构建的 UI 组件库 -- snake-design. 在 class 已经融入 React 生态 ...
- k8s-jenkins x CI/CD 动态创建slave---01
jenkins CI/CD(动态创建slave)简述: 由于之前管理kubernetes集群应用发布,用的是Gitlab-CI,用作开发环境管理还可以,生产环境管理发布,缺点太多,打包速度很慢.研究新 ...
- sprintboot+mybatis+@Mapper中in的使用方法
错误的使用方法: @Select("select goods_sn from ${tableName} where goods_sn in (#{skuStr})") public ...