[英]Downloading data from Oracle DB and exporting to csv file
我連接到某個 Oracle 數據庫並嘗試將數據導出到 csv 文件。 下面是我的 Python 代碼 -
import jpype
import jaydebeapi
import csv
# Assuming I already have established a connection -
# Connection variable is Conn
Curs = Conn.cursor()
Curs.execute("select * from Table")
Data = list(Curs.fetchall())
with open("mycsvfile.csv", "wb") as f:
w = csv.DictWriter(f, Data[0].keys())
w.writerow(dict((fn,fn) for fn in Data[0].keys()))
w.writerows(Data)
但是當我運行上面的代碼時,我得到了錯誤 -
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
AttributeError: 'tuple' object has no attribute 'keys'
你能幫我找到出路嗎?
非常感謝您的幫助
我正在使用此代碼使用 Python 創建一個 csv 文件(在我的情況下為 headers )。 我認為您應該嘗試cx_Oracle
,對我來說,這是從 Python 與 Oracle 數據庫交互的最佳方式。
import os
import sys
import cx_Oracle
db = cx_Oracle.connect('user/pass@host:port/service_name')
SQL = "select column1 , column2 , .... , columnn from table"
print(SQL)
cursor = db.cursor()
f = open("C:\myfile.csv", "w")
writer = csv.writer(f, lineterminator="\n", quoting=csv.QUOTE_NONNUMERIC)
r = cursor.execute(SQL)
#this takes the column names
col_names = [row[0] for row in cursor.description]
writer.writerow(col_names)
for row in cursor:
writer.writerow(row)
f.close()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.