1. 程式人生 > 其它 >python-連線oracle資料庫匯出資料表

python-連線oracle資料庫匯出資料表

'''
連線oracle資料庫匯出資料表為excel儲存在本地
'''

 1 import openpyxl
 2 from openpyxl import Workbook
 3 import cx_Oracle
 4 
 5 # 連線資料庫,獲取遊標
 6 con = cx_Oracle.connect('username/password@DBA01')
 7 cur = con.cursor()
 8 
 9 # 操作sql語句,將需要匯出的資料表名稱放在txt文件中,遍歷讀取每一行獲取表格名稱
10 with open("資料表名稱.txt","r") as f:
11     for line in
f.readline(): 12 try: 13 table = line.strip('\n') 14 sql = "select * from %s"%(table) 15 cur.execute(sql) # 執行sql查詢 16 except Exception as e: 17 print("匯出失敗資料表為%s,失敗原因為"%(table),e) 18 continue 19 results = cur.fetchall() #
獲取所有查詢結果 20 21 # 獲取行和列 22 rows = len(results) 23 if len(results): 24 cols = len(results[0]) 25 26 # 建立表格 27 wb = Workbook() 28 ws = wb.create_sheet("%s"%(table),0) 29 30 # 獲取表頭的欄位值,即標題行 31 db_title = [i[0] for i in cur.description]
32 for i,description in enumerate(db_title): 33 ws.cell(row=1, colum=1+i).value=description 34 35 # 迴圈查詢結果行和列,存在excel中 36 for m in range(rows): 37 for n in range(cols): 38 ws.cell(row=m+2,colum=n+1).value=results[2][n] 39 wb.save("d:/{}.xlsx".format(table)) 40 41 # 關閉遊標和連結 42 cur.close() 43 con.close()