如何在python 3.4中运行 sqlplus查询

How to run sqlplus query in python 3.4

我是 python 的新手,我正在尝试弄清楚如何连接到远程 Oracle DB 和 运行 使用 python 的 select 查询脚本。这是我想要实现的目标:

1) Connect to oracle db and run select query
2) Write the result to the file.

这是我使用的常规连接字符串:

sqlplus temapp/'password'@temappdb
and then I use a select query, lets say select * from employees where employ_id=12;

不太确定如何在 python 3.4 中实现此功能,在 2.7 中使用 MySQLdb module/library。

    **Here is my blueprint:** 
    #!/bin/python

    import sqlite3
    import sys
    import os

config = {
  'user': 'user',
  'password': '*****',
  'host': '127.0.0.1',
  'database': 'test',
  'raise_on_warnings': True,
}
    conn = sqlite3.connect('config') # not sure how to pass user and password
    c = conn.cursor()
    c.execute('select * from employees where employ_id=12')

2) 我不知道如何在文件中写入它,我的第一个猜测是使用 stdin 和 stdout 进行操作,我相信有更有效的方法来做到这一点。

orig_stdout = sys.stdout
out = open("/output.txt", 'w')
sys.stdout = out

c.execute('select * from employees where employ_id=12')
sys.stdout = orig_stdout
out.close()

有人可以建议更好的解决方案吗?

您将需要一个有效的 Oracle Client 或 Instant Client 安装和 cx_Oracle 模块。

然后试试这个:

import cx_Oracle
import csv

con = cx_Oracle.connect('temapp/password@temappdb')
cur = con.cursor()
cur.execute("SELECT * FROM emp")

with open("emp.csv", "wb") as csv_file:
    csv_writer = csv.writer(csv_file)
    csv_writer.writerow([i[0] for i in cur.description])  # write headers
    csv_writer.writerows(cur)