0
0

python-oracledb で CSV ファイルを出力

Posted at

python-oracledb とは

  • python-oracledb は cx_Oracle ドライバーの新しい名前で Oracle Database にアクセスするためのモジュール
  • デフォルトでは Oracle クライアント ライブラリは不要(Thin Mode)
  • ただし Thin の場合、Oracle データベース側が 12.1 以降なので 11g とかであれば Thick モードにする
  • Thick に変更するには接続前に初期化処理 oracledb.init_oracle_client() をする
  • Thick で必要な Oracle Instant Client はダウンロードして展開したらOK

Thick モードでCSV出力

pandas を使った例

oracle_to_pandas_csv.py
import oracledb
import pandas as pd

instantclient = "C:/instantclient_21_13"
oracledb.init_oracle_client(lib_dir=instantclient)
# tnsnames.ora のパスが通常と異なる場合には指定
# oracledb.defaults.config_dir = instantclient + "/network/admin"

sql = """
  SELECT 
    B.id 
   ,B.name
   ,B.address
  FROM
    db.b_info_table B
  WHERE
    B.id <= :id_code
"""

# 列名を取得する
def get_columns(cursor):
    columns = []
    for col in cursor.description:
        columns.append(col.name)
    return columns

# 
with oracledb.connect(user="xxxxxxx", password="xxxxxxxx", dsn="xxxxxxx") as connection:
    with connection.cursor() as cursor:
        results = cursor.execute(sql, id_code='99999999')
        #results = cursor.execute(sql)                    # Bind 変数のないSQLならこれだけで良い

        columns = get_columns(cursor)                     # 列名を取得
        data = cursor.fetchall()                          # 全データを取得

        df = pd.DataFrame(data, columns=columns)          # pandas dataframe に変換
        df.to_csv('oracle_pandas.csv', encoding='cp932', index=False)  # 文字コードは後続の用途次第
0
0
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
0
0