【问题标题】:how to use python cx_Oracle with spool如何将 python cx_Oracle 与 spool 一起使用
【发布时间】:2016-10-30 13:11:22
【问题描述】:

我正在使用 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:

【问题讨论】:

    标签: python oracle oracle11g cx-oracle


    【解决方案1】:

    “假脱机”命令非常特定于 SQL*Plus,在 cx_Oracle 或任何其他使用 OCI(Oracle 调用接口)的应用程序中不可用。但是,您可以执行类似的操作,而不会太麻烦。

    您可以创建您自己的从 cx_Oracle.Connection 子类化的 Connection 类和您自己的从 cx_Oracle.Cursor 子类化的 Cursor 类,它可以执行任何日志记录,并有一个特殊的命令“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")
    

    这应该让您对如何使用它有所了解。

    【讨论】:

    猜你喜欢
    • 2020-01-15
    • 2016-06-01
    • 2018-05-16
    • 1970-01-01
    • 1970-01-01
    • 2016-05-31
    • 2019-11-13
    • 2013-11-06
    • 1970-01-01
    相关资源
    最近更新 更多