我已连接到某些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'
您能帮我找到一条出路吗?
非常感谢您的帮助
答案 0 :(得分:0)
您可以使用sqlplus或SQLcl轻松生成csv:
https://oracle-base.com/articles/misc/sqlcl-format-query-results-with-the-set-sqlformat-command
https://www.thatjeffsmith.com/archive/2015/02/a-quick-4-1-trick-set-sqlformat/
答案 1 :(得分:0)
我正在使用此代码使用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()