PythonでOracleのデータをテキストに落とす
これはRubyレシピブックにはありません。
最初にデータの数を調べて表示し、それから内容をテキストファイルに落としていきます。Oracleでは、項目にデータがない時にはNoneが帰ってくるので、nullに変更しています。
環境は、Win2000、Python2.3上で実行しました。WindowsにはOracleのクライアントソフトとpythonのOracleアクセスのモジュールが必要です。
今回は、cx_Oracle というのを使いました。理由は、Windowsには何も考えなくてもインストールできるからです。
以下にあるようにDCOracleでも大丈夫だと思います。
http://www005.upp.so-net.ne.jp/nakagami/Memo/Oracle.html
import cx_Oracle,string
conn=cx_Oracle.connect(user/pass@domain)
cur=conn.cursor()
sqltxt="select count(*) from db_name where condition='xxxx'"
cur.execute(sqltxt)
linenum=cur.fetchone() ## get row number
print linenum
sqltxt="select * from db_name where condition='xxxx'"
cur.execute(sqltxt)
o=open('c:/temp/output.txt','w')
line=cur.fetchone()
i=0
while line:
oline=string.join([str(x) for x in line],'\t') ##Join with tab
outline=string.replace(oline,'None','')+'\n' ## replace None to Null
o.write(outline) ##write file
line=cur.fetchone() ##next line
print i,
i=i+1
cur.close()
o.close()
print "completed"