A Python script I made earlier. Output the record of the specified table to a CSV file.
See below for how to install 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:
#Get table column name
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))
#Get all records in the table
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()
Fetch 50 records in the table and output to a file. Processing ends when the number of fetches reaches 0. I feel that the way to write a fetch loop is not good enough. ..
Recommended Posts