请看以下步骤:
1. 安装cx_Oracle模块
在命令行中运行以下命令安装:
pip install cx_Oracle
2. 导入模块并连接Oracle数据库
import cx_Oracle
conn = cx_Oracle.connect('USER/PASSWORD@HOST:PORT/SERVICE_NAME') # USER为用户名,PASSWORD为密码,HOST为主机名,PORT为端口号,SERVICE_NAME为服务名
3. 准备SQL语句并执行
cursor = conn.cursor()
sql = 'SELECT * FROM TABLE'
cursor.execute(sql)
4. 获取查询结果
results = cursor.fetchall()
5. 写入CSV文件
import csv
with open('output.csv', 'w', newline='') as file:
writer = csv.writer(file)
writer.writerow([i[0] for i in cursor.description]) # 写入字段名称
writer.writerows(results)
以上就是将Oracle中数据导出到CSV文件的完整攻略,下面附上两个示例说明:
示例1:导出全表数据
import cx_Oracle
import csv
conn = cx_Oracle.connect('USER/PASSWORD@HOST:PORT/SERVICE_NAME')
cursor = conn.cursor()
sql = 'SELECT * FROM TABLE'
cursor.execute(sql)
results = cursor.fetchall()
with open('output.csv', 'w', newline='') as file:
writer = csv.writer(file)
writer.writerow([i[0] for i in cursor.description]) # 写入字段名称
writer.writerows(results)
cursor.close()
conn.close()
示例2:导出指定字段数据
import cx_Oracle
import csv
conn = cx_Oracle.connect('USER/PASSWORD@HOST:PORT/SERVICE_NAME')
cursor = conn.cursor()
sql = 'SELECT FIELD1, FIELD2, FIELD3 FROM TABLE'
cursor.execute(sql)
results = cursor.fetchall()
with open('output.csv', 'w', newline='') as file:
writer = csv.writer(file)
writer.writerow([i[0] for i in cursor.description]) # 写入字段名称
writer.writerows(results)
cursor.close()
conn.close()
希望以上内容对您有所帮助。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:Python使用cx_Oracle模块将oracle中数据导出到csv文件的方法 - Python技术站