pythonからpostgresqlにsqlファイルを実行しまくる

sqlファイルを全部処理したい

postgresqlsqlを順番に実行したいとき、一々一個ずつ実行するのはだるいですよね。 まとめて実行するプログラムを書きました。

PostgreSQL徹底入門 第3版

PostgreSQL徹底入門 第3版

入門 Python 3

入門 Python 3

ご査収ください。

# 必要なライブラリのインポート
from sqlalchemy import create_engine
from glob import glob
from datetime import datetime
from sqlalchemy import text

# sqlファイル読み込み
sql_files = glob(".\sql\*.sql")

# DBの接続設定
db_kind = "postgresql"
dbschema = "hoge_shcema"
user = "hoge_user"
password = "hoe_password"
server = "1.2.3.4"
port = "5432"
db_name = "hoge_database"

# DB接続文字列
con_str = db_kind + "://" + user + ":" + password + "@" + server + ":" + port + "/" + db_name

# DB接続
engine = create_engine(con_str, echo=True, connect_args={"options": "-csearch_path={}".format(dbschema)})

# SQL実行
for sql_file in sql_files:
    print(datetime.now().strftime("%Y/%m/%d %H:%M:%S") + " :" + sql_file + " exec start")
    with open(sql_file,"r") as f:
        f = open(sql_file)
        sql = f.read()
        engine.execute(text(sql))
    print(datetime.now().strftime("%Y/%m/%d %H:%M:%S") + " :" + sql_file + " exec end")

これで.\sql\フォルダにある全SQLを名前ソート順に実行してくれます。

ざっつおーる。せんきゅー。