Python PostgreSQL Insert Into Table
Insert Into Table
FILE: table_insert.py
import psycopg2
conn = psycopg2.connect(database = "kwikl3arn", user = "postgres", password = "post123", host = "localhost", port = "5432")
conn.autocommit = True
print ("Opened database successfully")
cur = conn.cursor()
cur.execute("INSERT INTO customers (name, address) VALUES('akon', 'USA') ")
conn.close()
RUN:
C:\Users\Your Name>python table_insert.py
Opened database successfully
Insert Multiple Rows
FILE: table_insert_multiple_rows.py
import psycopg2
conn = psycopg2.connect(database = "kwikl3arn", user = "postgres", password = "post123", host = "localhost", port = "5432")
conn.autocommit = True
print ("Opened database successfully")
cur = conn.cursor()
addr_list=[
('Betty', 'Green Grass 1'),
('Richard', 'Sky st 331'),
('Susan', 'One way 98'),
('Vicky', 'Yellow Garden 2'),
('Ben', 'Park Lane 38'),
('William', 'Central st 954'),
('Chuck', 'Main Road 989'),
('Viola', 'Sideway 1633')
]
for x,v in addr_list:
cur.execute("INSERT INTO customers (name, address) VALUES('{}','{}')".format(x,v))
conn.close()
RUN:
C:\Users\Your Name>python table_insert.py
Opened database successfully