PostgreSQL Python: Call PostgreSQL Functions
Summary: in this tutorial, you will learn how to call PostgreSQL functions from a Python program.
This tutorial picks up from where the Transaction Tutorial left off.
Calling a PostgreSQL function in Python
To call a PostgreSQL function from a Python program, you use the following steps:
First, create a new database connection to the PostgreSQL server by calling the connect()
function of the psycopg2
module.
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 function and the optionally pass values to the callproc()
method of the cursor
object:
Internally, the callproc()
method translates the function call and input values into the following statement:
Therefore, you can use the execute()
method of the cursor
object to call a function as follows:
Both statements have the same effect.
After that, process the result set returned by the function using the fetchone()
, fetchall()
, or fetchmany()
method.
Finally, call the close()
method of the cursor
and connection
objects to close the communication with the PostgreSQL database server:
Calling a PostgreSQL function example
Let’s take an example of calling a PostgreSQL function from Python.
1) Create a new function
First, open the Command Prompt on Windows or Terminal on Unix-like systems and connect to the suppliers
database:
Second, execute the following command to create a new function called get_parts_by_vendors()
that returns a list of parts by a specified vendor:
Notice that you can use any PostgreSQL client tools to create a function such as pgAdmin.
2) Create call_function.py module
First, create a new module in the project directory called call_function.py
:
Second, define a new function called get_parts()
that calls the get_parts_by_vendors()
function in PostgreSQL:
3) Call the call_function.py module
Run the following command to execute the call_function.py
module:
Output:
Download the project source code
Summary
- Use the
callproc()
method of thecursor
object to call a function in PostgreSQL from Python.