Help us understand the problem. What is going on with this article?

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

More than 3 years have passed since last update.

以前に作った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件になったら処理終了。
フェッチループの書き方がいまいちな気がする。。

Why do not you register as a user and use Qiita more conveniently?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away