how to insert rows into postgres code example
Example 1: postgresql, Rows, INSERT INTO
INSERT INTO table_name(column1, column2, …)
VALUES (value1, value2, …)
RETURNING *;Code language: SQL (Structured Query Language) (sql)
Example 2: insert record into table postgresql
try:
connection = psycopg2.connect(**postgres_credentials())
cursor = connection.cursor()
order_types = [(1,'SELL'),(2,'BUY')]
placeholders = ','.join(['%s']*len(order_types))
sql = f"""
INSERT INTO collection.instruction(id, side)
VALUES {placeholders}
"""
insert_statement = cursor.mogrify(sql, order_types)
print(insert_statement.decode('utf-8'))
cursor.execute(insert_statement)
connection.commit()
print('DB entries committed.')
except (Exception, psycopg2.DatabaseError) as error:
print(error)
finally:
if connection:
cursor.close()
connection.close()