オタク大学生の日記

愚痴の置き場(あと色々実験したりする場)

python + PostgreSQLの勉強中

データベース接続

def get_connection():
    connect_sent = 'host=' + address + ' port=' + port_number + \
                   ' dbname=' + db_name + ' user=' + user + ' password=' + password
    connection = psycopg2.connect(connect_sent)
    return connection

SQLファイルを読み込んでのテーブル作成

def create_table(connection, sqlfile):
    cur = connection.cursor()
    with open(sqlfile, 'r', encoding='utf-8') as f:
        sql_sents = f.read()
        print(sql_sents)
    cur.execute(sql_sents)
    connection.commit()
    cur.close()

実行したSQLファイル

CREATE TABLE IF NOT EXISTS purchase (
  id SERIAL NOT NULL,
  name VARCHAR(64) NOT NULL,
  date DATE NOT NULL,
  price INTEGER NOT NULL,
  PRIMARY KEY(id)
);

データの挿入

def insert_data(Connection):
    cur = connection.cursor()
    query = 'insert into Purchase (name, date, price) ' +\
            'values (%s, %s, %s);'
    cur.execute(query, ('test', '2019-07-15', '100'))
    connection.commit()
    cur.close()

テスト

if __name__ == '__main__':
    connection = get_connection()
    if connection:
        create_table(connection, '../PostgreSQL/init_table.sql')
        insert_data(connection)

テスト実行結果

mydb=> select * from purchase;
 id | name |    date    | price
----+------+------------+-------
  1 | test | 2019-07-15 |   100

こんな風にでもしないと自分でも色々忘れそうな気がしたのでメモ代わりに
コードにコメント書けばいいとかそういうツッコミはなしで