LoginSignup
0
1

More than 3 years have passed since last update.

投稿テスト6(Pandasを使ったPostgreSQL書き込み)

Posted at

技術メモ

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)
0
1
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
1