LoginSignup
3
5

More than 5 years have passed since last update.

Oracleのテーブルのレコード全件をCSVファイルに出力するPythonスクリプト

Posted at

以前に作ったPythonスクリプト。
指定したテーブルのレコードをCSVファイルに出力する。

環境

  • CentOS 6.4
  • Python 3.3.0
  • Oracle Client 11.2.0.3.0
  • ライブラリ: cx_Oracle

cx_Oracleのインストール方法は以下参照。
http://mokky14.hatenablog.com/entry/2014/12/17/150854

スクリプト

tbl2csv.py
#!/usr/bin/python3

import cx_Oracle
import sys
import csv
from itertools import chain

argvs = sys.argv
argc = len(argvs)
if argc != 2:
  print('Usage: %s TableName' % argvs[0])
  quit()

table_name = argvs[1].upper()
file_name = table_name + '_data.csv'

with cx_Oracle.connect('scott','tiger','xx.xx.xx.xx/tns_service_name') as conn:
  # テーブルの列名取得
  column_name_sql = 'select column_name from user_tab_columns where table_name = :tbl'
  cur_columns = conn.cursor()
  cur_columns.execute(column_name_sql, tbl=table_name)
  columns = cur_columns.fetchall()
  cur_columns.close()
  columns = tuple(chain.from_iterable(columns))

  # テーブルのレコード全件取得
  data_sql = 'select * from %s' % table_name
  cur_data = conn.cursor()
  cur_data.execute(data_sql)
  with open(file_name, 'w') as f:
    csv_writer = csv.writer(f)
    csv_writer.writerow(columns)
    while 1:
      rows = cur_data.fetchmany(50)
      if len(rows) == 0:
        break
      csv_writer.writerows(rows)
  cur_data.close()

テーブルのレコード50件ずつfetchしてファイル出力。フェッチ件数が0件になったら処理終了。
フェッチループの書き方がいまいちな気がする。。

3
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
5