-
Notifications
You must be signed in to change notification settings - Fork 0
/
04_update_table.py
43 lines (35 loc) · 1.18 KB
/
04_update_table.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#!/usr/bin/python
import psycopg2
from config import config
#http://www.postgresqltutorial.com/postgresql-python/update/
def update_vendor(vendor_id, vendor_name):
""" update vendor name based on the vendor id """
sql = """ UPDATE vendors
SET vendor_name = %s
WHERE vendor_id = %s"""
conn = None
updated_rows = 0
try:
# read database configuration
params = config()
# connect to the PostgreSQL database
conn = psycopg2.connect(**params)
# create a new cursor
cur = conn.cursor()
# execute the UPDATE statement
cur.execute(sql, (vendor_name, vendor_id))
# get the number of updated rows
updated_rows = cur.rowcount
# Commit the changes to the database
conn.commit()
# Close communication with the PostgreSQL database
cur.close()
except (Exception, psycopg2.DatabaseError) as error:
print(error)
finally:
if conn is not None:
conn.close()
return updated_rows
if __name__ == '__main__':
# insert one vendor
updated_rows = update_vendor(vendor_id=1, vendor_name='3M corp')