import psycopg2
#DB connection information
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)
After executing the above code, even if I check the table, it is not inserted ...
If you execute the query output by print (sql_sentence) directly from zsh, it will be inserted properly.
INSERT INTO slip(content, id, number) values('{"billing_sum":3257.21}', '111011111110000008001', '14');
INSERT 0 1
After executing the cur object, commit () the psycopg2.connect object.
import psycopg2
#DB connection information
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() #← This line
Transactions are enabled by default in psycopg2, so it will not be reflected unless you commit. You must set autocommit = True to disable transactions.
Recommended Posts