2016-10-30 7 views
0

私はpython3.4を使用してOracle(11g)/ sql開発者と対話しています。 cx_OracleがsqlPlusステートメントを処理できないことは本当ですか?それはページhttps://sourceforge.net/p/cx-oracle/mailman/message/2932119/そうだと思われる。spoolでpython cx_Oracleを使用する方法

どうすれば私たちは 'spool'コマンドをPythonで実行できますか?

コード:

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:

答えて

0

"スプール" コマンドは、SQL * Plusのに非常に固有のものであり、cx_Oracleまたはその他では使用できません。 OCI(Oracle Call Interface)を使用するアプリケーション。しかし、あまりにも厄介なことなしに、同様のことをすることができます。

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") 

これはどこに行けばいいか分かります。

+0

ありがとうございました!それは本当に役立ちます!私はあなたがbitbucketのウェブサイトでいくつかのpacakgesを開発したのを見ました。それらは素晴らしかった!このような状況でパッケージを使用することはできますか?私はコーディングがあまりよくないので、自分で書くのは難しいかもしれません.... – Xiaoqing

+0

よろしくお願いします。このパッケージは、使用しているSQLとバインド変数を記録します:https://bitbucket.org/anthony_tuininga/cx_pyoraclelib/src/dda6bfb0217bc48ea7c20cb763b3385e8fc9bfaa/cx_OracleEx.py?at=default&fileviewer=file-view-default –

+0

これが出力されます。 SQL文としてのクエリの結果。うまくいけば、それらのうちのいくつかがあなたを助けるでしょう:https://bitbucket.org/anthony_tuininga/cx_oracletools/src/d0b454fa1a020620f43f88ea15bd4c37a6ec8e19/DumpData.py?at=default&fileviewer=file-view-default –

関連する問題