• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

python从Oracle读取数据生成图表

python 搞代码 4年前 (2022-01-09) 31次浏览 已收录 0个评论

初次学习python,连接Oracle数据库,导出数据到Excel,再从Excel里面读取数据进行绘图,生成png保存出来。

1、涉及到的python模块(模块安装就不进行解释了):

import os
import cx_Oracle
import openpyxl
import time
import csv
import xlrd
from matplotl<em>本文来源gao.dai.ma.com搞@代*码(网$</em>ib import pyplot as plt
from matplotlib import font_manager

2、连接数据库

oracle客户端要根据自己python对应的版本进行下载

import os
os.environ['NLS_LANG'] = 'SIMPLIFIED CHINESE_CHINA.UTF8' #字符转换,如果配置了环境变量这里可用不要
os.environ['TNS_ADMIN'] = 'D:\\Python\\instantclient_12_2' #oracle客户端,如果配置了环境变量这里可用不要
os.environ['Path'] = 'D:\\Python\\instantclient_12_2' #自己电脑oracle客户端所在位置

import cx_Oracle

# 方法一:用户名、密码和监听分开写
#  conn=cx_Oracle.connect('username/password@host/orcl')  #连接数据库

# 方法二:用户名、密码和监听写在一起
  conn = cx_Oracle.connect('username/password@host:1521/ORCL') # utf-8显示中文

#方法三:配置监听并连接
#  tns=cx_Oracle.makedsn('host',1521,'orcl',encoding = 'utf-8',nencoding = "UTF-8")
#  conn=cx_Oracle.connect('username','password',tns)

curs=conn.cursor()     #获取cursor
printHeader = True # include column headers in each table output
sql="select b.name,sum(a.tot_qty) from m_retail a ,c_store b " \
  "where a.c_store_id=b.id and a.billdate=20200923 group by b.name" #sql语句
x=curs.execute(sql)             #使用cursor进行各种操作
rows= x.fetchall()
for row in rows:
  print(row)

3、创建Excel文件,读取SQL文件,将数据写入Excel保存到本地

def export_excel(sql,fileName):
  rr = curs.execute(sql)
  rows = curs.fetchall()

  #获取字段名
  title = [ i[0] for i in curs.description ]

  #创建excel表
  wb = openpyxl.Workbook()
  ws = wb.active

  #插入字段名到第一行
  for c in range(len(title)):
    ws.cell(1,c+1,value = title[c])

  #写入查询数据
  for r in range(len(rows)):
    for c in range(len(rows[r])):
      if rows[r][c]: #值不为空时写入,空值不写入
        ws.cell(r+2,c+1,value=str(rows[r][c])) #str()防止用科学计数法写入造成信息丢失
  #
  # #保存sql脚本
  # ws1 = wb.create_sheet('sql')
  # ws1.cell(1,1,value=sql)
  #
  wb.save(fileName)
  wb.close()
  curs.close()

if __name__ == '__main__':
# 方法一:用户名、密码和监听分开写
#  conn=cx_Oracle.connect('username/password@host/orcl')  #连接数据库

# 方法二:用户名、密码和监听写在一起
  conn = cx_Oracle.connect('username/password@host:1521/ORCL') # utf-8显示中文

#方法三:配置监听并连接
#  tns=cx_Oracle.makedsn('host',1521,'orcl',encoding = 'utf-8',nencoding = "UTF-8")
#  conn=cx_Oracle.connect('username','password',tns)

  curs= conn.cursor()
  #打开sql文件获取sql语句
  with open('零售查询.sql',encoding= 'utf-8') as sql_0:#encoding= 'utf-8'
    sql = sql_0.read()
  # sql = "select b.name as 店仓,sum(a.tot_qty) as 数量 from m_retail a ,c_store b " \
  #    "where a.c_store_id=b.id and a.billdate=20201010 group by b.name"
  cur_date = time.strftime("%Y-%m-%d", time.localtime())#"%Y-%m-%d-%H%M%S",取值日期
  wjm='零售2'+cur_date+'.xlsx'
  export_excel(sql,wjm)
  conn.close()

4、打开刚刚保存的Excel文件,且读取需要的数据

# 打开文件
data = xlrd.open_workbook(wjm)
cur_month = time.strftime("%m", time.localtime())#取值月份
# 查看工作表
# data.sheet_names()
# print("sheets:" + str(data.sheet_names()))
# 通过文件名获得工作表,获取工作表Sheet
# table = data.sheet_by_name(Sheet1)
table =data.sheet_by_index(0)#默认读取sheet1

cel_A1=table.cell(0,0)#取指定单元格的值
cel_B1=table.cell(0,1)
col_A=table.col_values(0,1)#取指定列的值
col_B=table.col_values(1,1)#
col_B = [ int(x) for x in col_B ]#文本转数字
# print(cel_A1)
# print(col_B)
# print("整行值:" + str(table.row_values(0)))
# print("整列值:" + str(table.col_values(0,1)))
# print("整列值:" + str(table.col_values(1,1)))
# print(col_A)

搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:python从Oracle读取数据生成图表
喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址