在日常的工作中,经常接到开发同事查询生产SQL的请求,公司又不允许对开发开放查询SQL的权限,并且查询的堡垒机又很慢,计划做一个可以自动查询SQL的小工具,一周内完成吧。

  大概功能实现了,一些涉及敏感的信息已去掉。

#encoding:utf-8
import cx_Oracle
import csv
import xlwt
import xlrd
import zipfile
import time
import xlsxwriter
from datetime import datetime
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import smtplib
import sys
import os reload(sys)
sys.setdefaultencoding('gbk')
username = ''
password = ''
epcis = ''
epods = ''
cxcc = ''
nba4ot = ''
claim = ''
sqlfile ='select.sql'
#date_now=datetime.now().strftime("%Y%m%d%H%M")
#zipfilename ='查询结果_'.decode('utf-8').encode('gbk')+"_"+str(date_now)+".zip" #打开查询SQL文件
def sqlstr(sqlfile):
reSql=open(sqlfile,'r').read().strip()
'''for i in open(sqlfile,'r').readlines():
if i.startswith('#') == True: #忽略掉#号开头的行
pass
else:
selectsql = selectsql + i
reSql = selectsql.split(';')'''
print reSql
return reSql def selectdb(db,selectsql):
selectsql=sqlstr(sqlfile)
print selectsql
conn = cx_Oracle.connect(username,password,db)
cur = conn.cursor()
sql = cur.execute(selectsql)
listnew=[]
title = [i[0] for i in cur.description]
listnew.append(title)
sqllist = []
sqllist = sql.fetchall()
listnew.append(sqllist)
cur.close()
conn.close
return listnew #生成excel文件
def createxlsx(sqldate):
date_now=datetime.now().strftime("%Y%m%d%H%M")
xlsxfilename = '查询结果_'.decode('utf-8').encode('gbk')+str(date_now)+'.xlsx'
workbook = xlsxwriter.Workbook(xlsxfilename,{'constant_memory':True})
worksheet = workbook.add_worksheet()
worksheet.write_row(0,0,sqldate[0])
for row,row_date in enumerate(sqldate[1]):
worksheet.write_row(row+1,0,row_date)
workbook.close()
return xlsxfilename def zipFile(xlsxfilename):
date_now=datetime.now().strftime("%Y%m%d%H%M")
zipfilename ='查询结果_'.decode('utf-8').encode('gbk')+"_"+str(date_now)+".zip"
f = zipfile.ZipFile(zipfilename,'w',zipfile.ZIP_DEFLATED)
zippath = "D:\Python27"
zipfilelist = []
for i in os.listdir(zippath):
if os.path.isfile(i):
zipfilelist.append(i)
for files in zipfilelist:
if xlsxfilename in files:
f.write(files)
os.remove(files)
f.close()
return zipfilename def sendmail(zipfilename):
msg = MIMEMultipart()
att1_name=zipfilename
att1 = MIMEText(open(zipfilename,'rb').read(),'base64','gb2312')
att1["Content-Type"] = 'application/octet-stream'
att1["Content-Disposition"]='attachment;filename=%s'% att1_name.encode('gbk')
msg.attach(att1) msg['to']='dingxiyu024@pingan.com.cn'
msg['from']='dingxiyu024@pingan.com.cn'
msg['subject']="SQL查询结果".decode('utf-8').encode('gbk')
try:
server=smtplib.SMTP()
server.connect('mailgw2.paic.com.cn')
server.login('','')
server.sendmail(msg['from'],msg['to'],msg.as_string())
server.quit()
print 'send mail successful.'
except Exception,e:
print str(e) def main():
sendmail(zipFile(createxlsx(selectdb(epcis,sqlfile)))) if main()=='__main__':
main()

20170506计划-----(基于python查询oracle语句)的更多相关文章

  1. 基于python实现Oracle数据库连接查询操作

    使用python语言连接Oracle数据库配置 #coding:utf-8 import cx_Oracle as oracle db=oracle.connect('root/123456@192. ...

  2. [Python]查询oracle导出结果至Excel并发送邮件

    环境:Linux +python2.7+oracle11g 1.提前安装xlwt(excel写入操作模块),cx_Oracle(oracle操作模块) cx_Oracle的安装步骤详见链接:https ...

  3. oracle -- 查询执行计划,判读查询语句优劣

    以oracle的scott账户:找到员工表中薪水大于本部门平均薪水的员工为例 多表查询方式: select e.empno, e.ename, e.sal, d.avgsal from emp e, ...

  4. [转载]T-SQL(Oracle)语句查询执行顺序

    原文链接:http://blog.sina.com.cn/s/blog_61c006ea0100mlgq.html sql语法的分析是从右到左,where子句中的条件书写顺序,基本上对sql性能没有影 ...

  5. python操作oracle数据库-查询

    python操作oracle数据库-查询 参照文档 http://www.oracle.com/technetwork/cn/articles/dsl/mastering-oracle-python- ...

  6. 查询Oracle正在执行的sql语句

    --查询Oracle正在执行的sql语句及执行该语句的用户 SELECT b.sid oracleID, b.username 登录Oracle用户名, b.serial#, spid 操作系统ID, ...

  7. 【转】如何解决plsql查询oracle数据库语句where条件带有中文无法匹配结果

    一.问题描述 之前使用PLSQL查询oracle数据库可以正常查询统计结果,由于换了个电脑,重新安装之后,同样的sql查询语句同一个数据库,无法正常查询结果,如下图所示 二.解决办法 1. 查询数据当 ...

  8. Python连接Oracle数据查询导出结果

    python连接oracle,需用用到模块cx_oracle,可以直接pip安装,如网络不好,可下载离线后本地安装 cx_oracle项目地址:https://pypi.org/project/cx_ ...

  9. Oracle 查询(SELECT)语句(一)

    Ø  简介 本文介绍 Oracle 中查询(SELECT)语句的使用,在 SQL 中 SELECT 语句是相对内容较多的,也是相对比较复杂一点的,所以这里拿出来单独学习. 首先,我们先来理一下思路,我 ...

随机推荐

  1. C# 面试知识点网络文档整理

    一 C# .NET技术 1.ASP.NET MVC如何控制权限? 2.C#.NET中的CTS.CLS和CLR? 3.什么是多线程,如何创建和如何使用?请写一个多线程单例模式? 4.什么是单例模式? 5 ...

  2. Java Native调用C方法

    1.通过JNI生成C调用的头文件:Java源码: import java.io.File; public class Test { static { System.load("D:" ...

  3. SAML2.0 SP端处理

    sso response解析 import java.io.ByteArrayInputStream; import java.io.InputStream; import java.security ...

  4. pyinstaller 打包生成exe之后运行提示‘no module name 'xxx'’错误

    python 3.7 pyinstaller 3.4 具体情况: pycharm中点击运行可成功执行,生成正确结果,没有报错. 双击run.py(程序运行的主文件),运行,可生成正确结果,没有报错. ...

  5. 虚拟机上安装django链接Pycharm(版本差异有所差异)

    第一,启动虚拟机,配置好虚拟机 第二,workon查看安装那些虚拟环境 第三,创建虚拟环境命令:mkvirtualenv -p /usr/bin/ python3 my_djangou 第四,进入虚拟 ...

  6. C++使用指针的优点

    使用指针可以带来如下的好处: (1)可以提高程序的编译效率和执行速度,使程序更加简洁. (2)通过指针被调用函数可以向调用函数处返回除正常的返回值之外的其他数据,从而实现两者间的双向通信. (3)利用 ...

  7. JUnit4源码学习笔记

    先上一个在Spring-test下运行的调用栈 自底向上: JUnitStarter IDEA对JUnit的支持,调用JUnitCore.run(Runner),将注解@RunWith指定的Runne ...

  8. stm32 HAL库笔记(一)——串口的操作

    昨天分析了普通io口的使用,和初始化代码流程,回顾一下,首先定义一个配置io口功能的结构体,然后开启时钟,再去配置这个结构体里面的各个成员变量,每个成员变量都有很多种选择,可以看各个成员变量 后面的注 ...

  9. django 之 ContentType的使用

    1. ContentType 是干什么用的呢: 1. ContentType: 主要的作用就是Django orm的创建表的时候,可以方便多表查询使用,简化多表查询的过程 2.ContentType ...

  10. Java学习随笔(2)--爬虫--天气预报

    public class Spiderweather { public static void main(String[] args) { List<String> list = null ...