Learning python for the first time, connecting to an Oracle database, exporting data to Excel, and then reading data from inside Excel for plotting, generating a png and saving it.
1, the python module involved (module installation will not be explained):
import os import cx_Oracle import openpyxl import time import csv import xlrd from matplotlib import pyplot as plt from matplotlib import font_manager
2. Connecting to the database
The oracle client should be downloaded according to your python version.
import os ['NLS_LANG'] = 'SIMPLIFIED CHINESE_CHINA.UTF8' # Character conversion, if configured with environment variables available here do not ['TNS_ADMIN'] = 'D:\\Python\\instantclient_12_2' # oracle client, if configured with environment variables available here do not ['Path'] = 'D:\\Python\\instantclient_12_2' #The location of the oracle client on your computer import cx_Oracle # Method 1: Separate username, password and listener # conn=cx_Oracle.connect('username/password@host/orcl') #connect to database # Method 2: Username, password and listener written together conn = cx_Oracle.connect('username/password@host:1521/ORCL') # utf-8 display Chinese # Method 3: Configure listening and connecting # tns=cx_Oracle.makedsn('host',1521,'orcl',encoding = 'utf-8',nencoding = "UTF-8") # conn=cx_Oracle.connect('username','password',tns) curs=() # Get cursor printHeader = True # include column headers in each table output sql="select ,sum(a.tot_qty) from m_retail a ,c_store b " \ "where a.c_store_id= and =20200923 group by " #sql statement x=(sql) # Use cursor for various operations rows= () for row in rows: print(row)
3、Create Excel file, read SQL file, write data to Excel and save it locally.
def export_excel(sql,fileName): rr = (sql) rows = () # Get field name title = [ i[0] for i in ] #Create excel sheet wb = () ws = # Insert the field name into the first row for c in range(len(title)): (1,c+1,value = title[c]) # Write query data for r in range(len(rows)): for c in range(len(rows[r])): if rows[r][c]: # Write when value is not null, null value is not written (r+2,c+1,value=str(rows[r][c])) #str() Prevents loss of information when writing in scientific notation. # # save the sql script # ws1 = wb.create_sheet('sql') # (1,1,value=sql) # (fileName) () () if __name__ == '__main__': # Method 1: Separate username, password and listener # conn=cx_Oracle.connect('username/password@host/orcl') #connect to database # Method 2: Username, password and listener written together conn = cx_Oracle.connect('username/password@host:1521/ORCL') # utf-8 display Chinese # Method 3: Configure listening and connecting # tns=cx_Oracle.makedsn('host',1521,'orcl',encoding = 'utf-8',nencoding = "UTF-8") # conn=cx_Oracle.connect('username','password',tns) curs= () # Open sql file to get sql statement with open('retailquery.sql',encoding= 'utf-8') as sql_0:#encoding= 'utf-8' sql = sql_0.read() # sql = "select as store warehouse,sum(a.tot_qty) as quantities from m_retail a ,c_store b " \ # "where a.c_store_id= and =20201010 group by " cur_date = ("%Y-%m-%d", ())#"%Y-%m-%d-%H%M%S", value date wjm='Retail 2'+cur_date+'.xlsx' export_excel(sql,wjm) ()
4, just open the saved Excel file, and read the required data
# Open the file data = xlrd.open_workbook(wjm) cur_month = ("%m", ())# of months # View worksheet # data.sheet_names() # print("sheets:" + str(data.sheet_names())) # Get worksheet by file name, get worksheet Sheet # table = data.sheet_by_name(Sheet1) table =data.sheet_by_index(0)# Default reading of sheet1 cel_A1=(0,0)# Fetch the value of the specified cell cel_B1=(0,1) col_A=table.col_values(0,1)# Fetch the value of the specified column col_B=table.col_values(1,1)# col_B = [ int(x) for x in col_B ]# Text to numbers # print(cel_A1) # print(col_B) # print("Whole row values: " + str(table.row_values(0))) # print("Integer column values: " + str(table.col_values(0,1))) # print("Integer column values: " + str(table.col_values(1,1))) # print(col_A)
5. Drawing bar charts
#Set the Chinese character display when drawing #my_font=font_manager.FontProperties(fname=r"C:/Windows/Fonts/", size=18) ['']=['sans-serif'] ['-serif']=['simhei' ] [''] = '20' ['']=16 ['']=16 # Setting the graphic size (figsize=(20,8),dpi=80) # Plotting bar graphs (range(len(col_A)),col_B) # Setting the x-axis (range(len(col_A)),col_A) (cur_month+"Monthly sales distribution") #Add a title ("./sig_size3.png")# Save the drawing to the project directory ()
Results Showcase
Above is python read data from Oracle to generate charts in detail, more information about python generate charts please pay attention to my other related articles!