python-连接oracle查询数据并且把数据保存至excel,然后发送至邮箱

环境准备:
python:3.7
需要库:
cx_Oracle
pandas
库的下载地址:https://pypi.org/project/pandas/1.0.0/#files
oracle:11.2…0.4
本机上与服务器上的oracle客户端不一致,因此下载了instantclient这个东西,配置好tnsnames.ora文件,就可以使用cx_oracle连接oracle
下载地址为:https://www.oracle.com/cn/database/technology/instant-client.html

import cx_Oracle
import pandas
import smtplib
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
from email.header import Header
import time
def export_execl(sql,fileName):
    #插叙sql
    rs=cursor.execute(sql)
    #获取全部结果集
    rows=rs.fetchall()
    #获取字段名称,遍历cursor.description,结果是个元组,然后取元组的第一位,赋值给tilte,因此title是个列表
    title=[ i[0] for i in cursor.description ]
    # for i in cursor.description:
    #     print(i)
    #     print(i[0])
    # print(title)
    # print(type(title))

    #也可以这样写
    # dret = pandas.DataFrame.from_records(list(rows))
    # dret.to_excel("filename.xlsx", index=False, header=("app", "name"))
    # 创建表格
    write=pandas.ExcelWriter(fileName)
    #创建表格中的列名称
    #其中DataFrame包含三个参数,value为值,columns为列名称,index为行名称,其中index需要和行数一致
    #处理数据,把数据处理成表格的样子。
    df= pandas.DataFrame(rows,columns=title)
    # df= pandas.DataFrame(rows,index=['1','2','3','4'],columns=title)
    #往表格(write)中sheet1中写数据,并且命名sheet也名称
    df.to_excel(write,sheet_name='result',index=False)
    df_sql=pandas.DataFrame([sql])
    #往表格(write)中sheet2中写数据,并且命名sheet也名称
    df_sql.to_excel(write,sheet_name='sql',index=False)
    write.save()


def send_mail(subject,content,file):
    #发送人邮箱
    from_addr='2973@qq.com'
    #发送人密码(这个是qq邮箱授权码,获取方法需要登录QQ邮箱查看)
    passwd='czgqvbijb'
    #收件人邮箱
    to_addr='29734@qq.com'
    #邮箱服务器(这里是用SMTP发送)
    smtp_server='smtp.qq.com'
    #必须添加
    msg = MIMEMultipart()
    #正文内容
    txt=MIMEText(content,'plain','utf-8')
    #获取正文
    msg.attach(txt)
    #发件人邮箱抬头别称
    msg['From'] = Header("发件人", 'utf-8')
    #收件人邮箱抬头别称
    msg['To'] = Header("收件人", 'utf-8')
    #邮箱标题
    msg['Subject']=Header(subject)
    #########添加附件#############
    for x in file_name:
        #读取文件内容
        part = MIMEApplication(open(x, 'rb').read())
        #设置附件名称
        part.add_header('Content-Disposition', 'attachment', filename=x)
        #获取附件
        msg.attach(part)
    #邮箱服务器,端口为25
    server=smtplib.SMTP(smtp_server,25)
    #登录邮箱
    server.login(from_addr,passwd)
    #发送邮件
    server.sendmail(from_addr,to_addr,msg.as_string())
    #退出邮件
    server.quit()
#主程序
#因为客户端与oracle版本不一致,使用轻量客户端比较方便,这里配置对应的环境变量
os.environ['NLS_LANG']='SIMPLIFIED CHINESE_CHINA.ZHS16GBK'
os.environ['path']='F:\python_script\instantclient-basic-windows.x64-11.2.0.4.0\instantclient_11_2'
if __name__=="__main__":
    #连接oracle数据库
    conn = cx_Oracle.connect('USER','PASSWORD','127.0.0.1:1521/orcl')
    # 创建游标
    cursor = conn.cursor()
    #读取文本中的sql
    i=1
    file_name=[]
    w=1
    with open('dsjpt_search','r') as sql_1:
        for sql in sql_1:
            #导出sql中的数据如表中
            date=time.strftime('%Y%m%d%H',time.localtime())
            file_path='sql_out%s%s.xls'%(date,i)
            export_execl(sql,file_path)
            i=i+1
    #断开数据库
    cursor.close()
    conn.close()
    for w in range(i-1):
        w = w + 1
        print(w)
        file_name.append('sql_out%s%s.xls'%(date,w))
    send_mail('python_test_hc', 'hello word', file_name)





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值