【问题标题】:How to run sqlplus query in python 3.4如何在 python 3.4 中运行 sqlplus 查询
【发布时间】:2015-04-05 22:22:11
【问题描述】:

我是 python 新手,我想弄清楚如何连接到远程 oracle DB 并使用 python 脚本运行选择查询。这是我想要实现的目标:

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 模块/库。

    **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()

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

【问题讨论】:

    标签: python oracle sqlite select python-3.x


    【解决方案1】:

    您将需要一个正常工作的 Oracle 客户端或即时客户端安装以及 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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-12-13
      • 1970-01-01
      • 2016-02-22
      • 2020-10-23
      • 1970-01-01
      • 2014-06-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多