简体   繁体   English

从 Oracle DB 下载数据并导出到 csv 文件

[英]Downloading data from Oracle DB and exporting to csv file

I have a connection to some Oracle data base and trying to export the data to a csv file.我连接到某个 Oracle 数据库并尝试将数据导出到 csv 文件。 Below is my Python code -下面是我的 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)

But when I ran above code, I got error as -但是当我运行上面的代码时,我得到了错误 -

Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
AttributeError: 'tuple' object has no attribute 'keys'

Could you please help me to find a way out?你能帮我找到出路吗?

Many thanks for your help非常感谢您的帮助

I am using this code to create a csv file using Python ( in my case with headers ).我正在使用此代码使用 Python 创建一个 csv 文件(在我的情况下为 headers )。 I think you should try cx_Oracle , for me it is the best way to interact with Oracle databases from Python.我认为您应该尝试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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM