I am new to both python and SQL. What I want to do eventually is that user types a value to insert into a table in PostgreSQL. I have tried a few methods I could find,
- https://www.postgresql.org/docs/9.1/static/plpgsql-structure.html
- http://www.java2s.com/Code/PostgreSQL/Postgre-SQL/UsingavariableinanINSERT.htm
but I have not been able to successfully insert. This is what I have now:
import psycopg2
from config import config
def create_tables(a):
""" create tables in the PostgreSQL database"""
commands = (
"""
SET num 10,
INSERT INTO Hotel_A (date, Suite, StandardKing) VALUES ('2017-09-12', num, 3)
""",
"""
INSERT INTO Hotel_A (date, Suite, StandardKing) VALUES ('2017-09-29', 5, 3)
""",
"""
INSERT INTO Hotel_A (date, Suite, StandardKing) VALUES ('2017-09-23', 5, 3)
"""
)
conn = None
try:
# read the connection parameters
params = config()
# connect to the PostgreSQL server
conn = psycopg2.connect(**params)
cur = conn.cursor()
# create table one by one
for command in commands:
cur.execute(command)
# close communication with the PostgreSQL database server
cur.close()
# commit the changes
conn.commit()
except (Exception, psycopg2.DatabaseError) as error:
print(error)
finally:
if conn is not None:
conn.close()
HotelASuite = 10
if __name__ == '__main__':
create_tables(HotelASuite)
I want to do num = HotelASuite that is my goal.
Thank you so much for your help!. I am using Python 2.7 and PostgreSQL 9.6.