如何在假脱机中使用 python cx_Oracle

how to use python cx_Oracle with spool

我正在使用 python3.4 与 oracle(11g)/sql 开发人员进行交互。 cx_Oracle 确实无法处理 sqlPlus 语句吗?页面https://sourceforge.net/p/cx-oracle/mailman/message/2932119/好像是这么说的。

那么我们如何通过python执行'spool'命令呢?

代码:

import cx_Oracle
db_conn = cx_Oracle.connect(...)
cursor = db_conn.cursor()
cursor.execute('spool C:\Users\Administrator\Desktop\mycsv.csv')
...

错误:cx_Oracle.DatabaseError:ORA-00900:

"spool" 命令非常特定于 SQL*Plus,在 cx_Oracle 或任何其他使用 OCI(Oracle 调用接口)的应用程序中不可用。不过,您可以做类似的事情,不会太麻烦。

您可以从 cx_Oracle.Connection 创建自己的连接 class 子class 和从 cx_Oracle.Cursor 子class 子class 的游标] 将执行任何日志记录,并有一个特殊命令 "spool" 可以随意打开和关闭它。像这样:

class Connection(cx_Oracle.Connection):

    def __init__(self, *args, **kwargs):
        self.spoolFile = None
        return super(Connection, self).__init__(*args, **kwargs)

    def cursor(self):
        return Cursor(self)

    def spool(self, fileName):
        self.spoolFile = open(fileName, "w")


class Cursor(cx_Oracle.Cursor):

    def execute(self, statement, args):
        result = super(Cursor, self).execute(statement, args)
        if self.connection.spoolFile is not None:
            self.connection.spoolFile.write("Headers for query\n")
            self.connection.spoolFile.write("use cursor.description")

    def fetchall(self):
        rows = super(Cursor, self).fetchall()
        if self.connection.spoolFile is not None:
            for row in rows:
                self.connection.spoolFile.write("row details")

这应该会让您知道该去哪里。