首先得安装各种库。。。。
诸如mysql,pandas,numpy之类的了
我使用的pandas版本为pandas (0.16.2)
其中openpyxls版本为openpyxl (1.8.6)
其实到处mysql查询结果导出当然可以使用诸如sqllog,Navicat之类的客户端直接导出,简单快捷,下面的代码只是在需要定时并且以某种格式定期发送sql查询结果的环境下才存在的。
注:再者pandas当然还可以结合matplotlib生成漂亮的饼状图或者柱状图,只不过笔者暂时没有这个需求,所以没有写生成图片的部分
放代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import
pandas
import
pandas as pd
import
MySQLdb
import
MySQLdb.cursors
import
os
import
datetime
from
email.mime.text
import
MIMEText
from
email.mime.multipart
import
MIMEMultipart
import
smtplib
#返回SQL结果的函数
def
retsql(sql):
db_user
=
MySQLdb.connect(
'IP'
,
'用户名'
,
'密码'
,
'j数据库名(可以不指定)'
,cursorclass
=
MySQLdb.cursors.DictCursor(设置返回结果以字典的格式))
cursor
=
db_user.cursor()
cursor.execute(
"SET NAMES utf8;"
(设置字符集为utf
-
8
,不然在返回的结果中会显示乱码,即使数据库的编码设置就是utf
-
8
))
cursor.execute(sql)
ret
=
cursor.fetchall()
db_user.close()
return
ret
#生成xls文件的函数
def
retxls(ret,dt):
file_name
=
datetime.datetime.now().strftime(
"/path/to/store/%Y-%m-%d-%H:%M"
)
+
dt
+
".sql.xlsx"
dret
=
pd.DataFrame.from_records(ret)
dret.to_excel(filename,
"Sheet1"
,engine
=
"openpyxl"
)
###z注意openpyxl这个库可能在生成xls的时候出错,pip install openpyxls==1.8.6,其他版本似乎与pandas有点冲突,安装1.8.6的即可
print
"Ok!!! the file in"
,file_name
return
filename
#发送邮件的函数
##传入主题,显示名,目标邮箱,附件名
def
sendm(sub,cttstr,to_list,
file
):
msg
=
MIMEMultipart()
att
=
MIMEText(
open
(
file
,
'rb'
).read(),
"base64"
,
"utf-8"
)
att[
"Content-Type"
]
=
"application/octet-stream"
att[
"Content-Disposition"
]
=
'attachment; filename="sql查询结果.xlsx"'
msg[
'from'
]
=
'发件人地址'
msg[
'subject'
]
=
sub
ctt
=
MIMEText(cttstr,
'plain'
,
'utf-8'
)
msg.attach(att)
msg.attach(ctt)
try
:
server
=
smtplib.SMTP()
#server.set_debuglevel(1) ###如果问题可打开此选项以便调试
server.connect(
"mail.example.com"
,
'25'
)
server.starttls()
###如果开启了ssl或者tls加密,开启加密
server.login(
"可用邮箱用户名"
,
"密码"
)
server.sendmail(msg[
'from'
],to_list,msg.as_string())
server.quit()
print
'ok!!!'
except
Exception,e:
print
str
(e)
###想要查询的sql语句
sql
=
"""sql语句"""
#接收邮件的用户列表
to_list
=
[
'test1@example.com'
,
'test2@example.com'
]
#执行sql并将结果传递给ret
ret
=
retsql(sql)
#将结果文件路径结果传给retfile
retfile
=
retxls(ret,
"1"
)
#发送邮件
#发送sql语句内容
sendm(sub1,sub1,to_list,retfile1)
|
虽然上述代码还有很大的改动空间,但是能用并且已经用了,又不是很重要的部分,就不继续改进了。
本文转自 youerning 51CTO博客,原文链接:http://blog.51cto.com/youerning/1708941