LoginSignup
1
0

More than 3 years have passed since last update.

PythonからPostgreSQLのテーブルにINSERTする時にハマった話

Last updated at Posted at 2020-12-21

問題点

import psycopg2

# DB接続情報
postgre_user_name = "admin"
postgre_user_password = "password"
postgre_server_port = 5432
postgre_database_name = "hogefuga"

connection = psycopg2.connect(f"host=localhost port={postgre_server_port} dbname={postgre_database_name} user={postgre_user_name} password={postgre_user_password}")
cur = connection.cursor()

result = json.dumps(result)
id = 1234
number = 1234

sql_sentence = f"INSERT INTO slip(content, id, number) values('{result}', '{id}', '{number}');"
print(sql_sentence)
cur.execute(sql_sentence)

上記コード実行後、テーブルを確認してもインサートされていない…。

print(sql_sentence)で出力されたクエリをzshから直接実行するとちゃんとインサートされる。

INSERT INTO slip(content, id, number) values('{"billing_sum":3257.21}', '111011111110000008001', '14');
INSERT 0 1

解決方法

curオブジェクトをexecuteした後、psycopg2.connectオブジェクトをcommit()してあげる。

import psycopg2

# DB接続情報
postgre_user_name = "admin"
postgre_user_password = "password"
postgre_server_port = 5432
postgre_database_name = "hogefuga"

connection = psycopg2.connect(f"host=localhost port={postgre_server_port} dbname={postgre_database_name} user={postgre_user_name} password={postgre_user_password}")
cur = connection.cursor()

result = json.dumps(result)
id = 1234
number = 1234

sql_sentence = f"INSERT INTO slip(content, id, number) values('{result}', '{id}', '{number}');"
print(sql_sentence)
cur.execute(sql_sentence)
connection.commit() # ←この一行

psycopg2 ではデフォルトでトランザクションが有効になっているので commit を行わないと反映されない。トランザクションを無効にする場合は autocommit = True を設定する必要がある。

※トランザクションとは複数の処理を一つにまとめたもの。
一例として、銀行口座間の振り込みが挙げられる。
AさんからBさんに5,000円振り込みを行う場合、
①Aさんの口座から5,000円減額する
②Bさんの口座を5,000円増額する
どちらかだけの処理が成功したら困るので、一連の処理にまとめる。
トランザクションは成功か失敗かしかない。

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