psycopg2 の execute は、commitの前に連続して実行できる。そのため、以下のように、sql文をforループで回すことができる。
import psycopg2 import os from dotenv import load_dotenv load_dotenv('../.env') PSQL_PASSWORD = os.getenv('PSQL_PASSWORD') connection = psycopg2.connect( host='localhost', user='postgres', password=PSQL_PASSWORD ) cur = connection.cursor() sql1 = "CREATE TABLE IF NOT EXISTS person1 ( \ id SERIAL PRIMARY KEY, \ name TEXT NOT NULL, \ data BYTEA \ );" sql2 = "CREATE TABLE IF NOT EXISTS person2 ( \ id SERIAL PRIMARY KEY, \ name TEXT NOT NULL, \ data BYTEA \ );" sqls = [sql1, sql2] for sql in sqls: cur.execute(sql) connection.commit() cur.close() connection.close()
$ python3 migration.py
# \dt
List of relations
Schema | Name | Type | Owner
——–+———-+——-+———-
public | person1 | table | postgres
public | person2 | table | postgres
なるほどー