import psycopg2
import csv
import os
import glob
# =============================================================================
# parameters
# =============================================================================
# テーブル定義CSVのファイルパス
DDL_DIRPATH = '/table定義/'
# postgreSQLの接続情報
postgres_config = {
'user': 'postgres',
'pass': '123qwe!',
'host': 'localhost',
'port': '5432',
'db': 'postgres'
}
# =============================================================================
# function
# =============================================================================
# =============================================================================
# main
# =============================================================================
# テーブル定義CSVが入ったフォルダからCSVファイルのファイル名リストを作成
ddlfile = []
os.chdir(DDL_DIRPATH)
ddlfile.extend(glob.glob('*.csv'))
# 1テーブル定義CSVにつき、1テーブルを新規作成
for i in ddlfile:
print(i)
csv_file = open("/Users/KODAI/Desktop/table定義/"+i, "r", encoding="ms932", errors="", newline="" )
ddl_file = csv.reader(csv_file, delimiter=",", doublequote=True, lineterminator="\r\n", quotechar='"', skipinitialspace=True)
# テーブル名を取ってくるところは既存コードを流用する ※編集
head = next(ddl_file)
print(head)
table_name = head[1]
next(ddl_file)
next(ddl_file)
### CREATE TABLE 文を作成開始
sql_create_table='CREATE TABLE '+table_name+' ('
# CSVファイルから各カラムの設定を記述
for row in ddl_file:
# CSVに短縮して書かれている定義は、正しい型名に修正する
if row[1]=='DOUBLE':
row[1] = 'DOUBLE PRECISION'
# 各カラムの定義作成
sql_create_table += '\"' + row[0] +'\"' + ' ' +row[1] + ','
# 末尾のカンマを削除して、括弧を閉じる
sql_create_table = sql_create_table[:-1]
sql_create_table += ')'
### CREATE TABLE 文を作成完了
# postgreSQLへ接続
config = ' user={user} dbname={db} password={pass}'.format(**postgres_config)
# with構文でclose()がいらない形で記述
with psycopg2.connect(config) as conn:
conn.autocommit = True #commit()不要で実行できるよう設定
with conn.cursor() as cur:
# 作成したCREATE TABLE 文を実行
cur.execute(sql_create_table)