PostgreSQL Python: Call Stored Procedures
Summary: in this tutorial, you will learn how to call PostgreSQL stored procedures from a Python program.
This tutorial picks up from where the Call PostgreSQL Functions Tutorial left off.
Steps for calling a PostgreSQL stored procedure in Python
To call a PostgreSQL stored procedure in a Python program, you follow these steps:
First, create a new database connection to the PostgreSQL database server by calling the connect()
function:
The connect()
method returns a new instance of the connection
class.
Next, create a new cursor by calling the cursor()
method of the connection
object.
Then, pass the name of the stored procedure and optional input values to the execute()
method of the cursor
object. For example:
If your stored procedure does not accept any parameters, you can omit the second argument like this:
After that, call the commit()
method to commit the transaction:
Finally, call the close()
method of the cursor
and connection
objects to close the connection to the PostgreSQL database server.
If you use context managers, you don’t need to explicitly call the close()
method of the cursor and connection.
Calling a stored procedure example
Let’s take an example of calling a PostgreSQL stored procedure in Python.
1) Create a new stored procedure
First, open the Command Prompt on Windows or Terminal on Unix-like systems.
Second, connect to the suppliers
database on the local PostgreSQL server:
Third, create a new stored procedure called add_new_part()
:
2) Create the call_stored_procedure.py module
First, create a new module called call_stored_procedure.py
file in the project directory.
Second, define the following add_part()
function that calls the add_new_part()
stored procedure from the suppliers
database:
3) Execute the Python module
Execute the following command to run the call_stored_procedure.py
module:
4) Verify the result
Execute the following statement to retrieve data from the parts
, vendors
, and vendor_parts
tables to verify the result:
Download the project source code
Summary
- Use the
execute()
method of acursor
object to execute a stored procedure call. - Use the
CALL sp_name(arguments)
syntax to construct a stored procedure call.