【问题标题】:Write output of a python script calling a sql script to a file将调用 sql 脚本的 python 脚本的输出写入文件
【发布时间】:2016-09-20 13:25:53
【问题描述】:

我正在同时学习 python 和 sql。 ;) 下面的 python 脚本调用一个 sql 脚本。我试图弄清楚如何从查询中获取输出以转到 csv。我已经做到了这一点:


#!/usr/bin/env python
import cx_Oracle
import sys
import csv
import os.path
import subprocess
con = cx_Oracle.connect('creden/tials@(DESCRIPTION =(ADDRESS_LIST =(ADDRESS =(PROTOCOL = TCP)(Host =server.work.net)(Port = 3453)))(CONNECT_DATA = (SID = SQLTEST)))')
cur=con.cursor()

f=open('/usr/local/src/sql/script_01.sql')
    full_sql=f.read()
    sql_commands=full_sql.split(";")
for sql_command in sql_commands:
    cur.execute(sql_command)

# Here is where the magic should happen
# The output of above should go to the 'test_query' file
query_results = <OUTPUT OF FOR LOOP>

c=csv.writer(open("/home/user/sqlplus/test_query/test_query.csv","w"),delimiter=";",lineterminator="\r\n")
c.writerows(query_results)

cur.close()

谁能告诉我我错过了什么?

【问题讨论】:

  • 由于我们无法访问您的 Oracle 数据库,因此我们看不到出了什么问题。
  • sql脚本运行正常,就是不知道怎么把cur.execute(sql_command)的返回结果直接传给csv。
  • 您应该在每次执行某些操作时获取结果。因此,您可以在 for 循环中添加 results = cur.fetchall()query_results.append(results) 之类的内容。

标签: python sql oracle


【解决方案1】:

也许这会对你有所帮助。 Documentation

有一个函数 fetchall() 获取查询结果的所有行。

你可以把它当作

cur.execute("sql_command")
query_result = cur.fetchall()

query_result 将是元组类型。

这将一次只包含一个命令的结果。

现在您可以使用列表。并追加所有结果。

例如

results = []
for sql_command in sql_commands:
    cur.execute(sql_command) #sql_command is of type string
    query_result = cur.fetchall()
    print(query_result)
    #query_result will be tuple so select which part of the tuple you need. e.g query_result[0], query_result[1] etc.
    results.append(query_result[0]) #change index according to your need

现在在 for 循环结束时,您将获得包含所有查询输出的列表(即结果)。

通过在结果上使用另一个 for 循环(这是一个列表),您可以一个一个地获取每个查询的结果 并且可以写入csv文件。

我现在不知道如何处理 csv 文件。也许您需要在每次迭代时保存 csv 文件。 我希望你能处理好这个。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-09-02
    • 2019-03-16
    • 1970-01-01
    • 1970-01-01
    • 2017-01-09
    • 1970-01-01
    • 2015-08-22
    • 1970-01-01
    相关资源
    最近更新 更多