技術メモ
DataFrameの中身をPostgreSQLに書き込むには、pandas.DataFrameのメソッドto_sqlを使用
ただし、to_sqlのデフォルトのデータベースはSQLiteのため、PostgreSQLに変更して使用する
replaceを使用する場合は。もともとのテーブルを削除しないといけないので注意
サンプルコード
from sqlalchemy import create_engine
# データベースの接続情報
postgres_config = {
'user': 'postgres',
'pass': '123qwe!',
'host': 'localhost',
'port': '5432',
'db': 'postgres'
}
# PostgreSQLへの接続設定
engine = create_engine('postgresql://{user}:{pass}@{host}:{port}/{db}'.format(**postgres_config))
# PostgreSQLへの書き込み
df.to_sql('データベース名', con=engine, if_exists='appendまたはreplace', index=False)
サンプルコード
import os
import glob
import pandas as pd
from sqlalchemy import create_engine
# =============================================================================
# parameters
# =============================================================================
# 投入するCSVのファイルパス
CSV_DIRPATH = '/XXX/'
# INSERTするデータの日付YYYYMMDD
tgt_date = ['20210115','20210116']
# データベースの接続情報
postgres_config = {
'user': 'postgres',
'pass': '123qwe!',
'host': 'localhost',
'port': '5432',
'db': 'postgres'
}
# =============================================================================
# function
# =============================================================================
# =============================================================================
# main
# =============================================================================
for date in tgt_date:
# CSVファイルのファイル名リストを作成
csvfile = []
os.chdir(CSV_DIRPATH + date)
csvfile.extend(glob.glob('*.csv'))
for i in csvfile:
# ファイル名から書き込みテーブル名を取得
table_name = i[:8] + i[10:-4]
print(table_name)
df = pd.read_csv(CSV_DIRPATH + date +'/'+ i, sep=',',encoding = "shift-jis")
print(df.head(3))
# PostgreSQLへの接続設定
engine = create_engine('postgresql://{user}:{pass}@{host}:{port}/{db}'.format(**postgres_config))
# PostgreSQLに書き込む
df.to_sql(table_name, con=engine, if_exists='append', index=False)