-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path06_call_stored_procedure.py
71 lines (49 loc) · 1.75 KB
/
06_call_stored_procedure.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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
#!/usr/bin/python
import psycopg2
from config import config
def get_parts(vendor_id):
""" get parts provided by a vendor specified by the vendor_id """
conn = None
try:
# read database configuration
params = config()
# connect to the PostgreSQL database
conn = psycopg2.connect(**params)
# create a cursor object for execution
cur = conn.cursor()
# another way to call a stored procedure
# cur.execute("SELECT * FROM get_parts_by_vendor( %s); ",(vendor_id,))
cur.callproc('get_parts_by_vendor', (vendor_id,))
# process the result set
row = cur.fetchone()
while row is not None:
print(row)
row = cur.fetchone()
# close the communication with the PostgreSQL database server
cur.close()
except (Exception, psycopg2.DatabaseError) as error:
print(error)
finally:
if conn is not None:
conn.close()
if __name__ == '__main__':
get_parts(1)
"""
Calling a stored procedure example
The following get_parts_by_vendors() stored procedure returns a list of parts provided by a specified vendor.
copy and paste this in pgsql command line to generate the function then you can run python ocde to call it!!! :-)
----------------------
CREATE OR REPLACE FUNCTION get_parts_by_vendor(id integer)
RETURNS TABLE(part_id INTEGER, part_name VARCHAR) AS
$$
BEGIN
RETURN QUERY
SELECT parts.part_id, parts.part_name
FROM parts
INNER JOIN vendor_parts on vendor_parts.part_id = parts.part_id
WHERE vendor_id = id;
END; $$
LANGUAGE plpgsql;
-----------------------------
The following get_parts() function calls the get_parts_by_vendors() stored procedure:
"""