[파이썬] Psycopg2에서 Stored procedures 호출

Stored procedures are precompiled and stored database objects that can be called to execute specific operations. They are commonly used in database management systems like PostgreSQL to perform complex tasks efficiently.

Psycopg2 is a popular Python library that provides a PostgreSQL adapter for Python. It allows us to connect to a PostgreSQL database and perform various operations, including calling stored procedures.

In this blog post, we will explore how to call stored procedures using Psycopg2 in Python.

Prerequisites

Before we get started, make sure you have Psycopg2 installed. You can install it using pip:

pip install psycopg2

Connecting to the Database

First, let’s establish a connection to the PostgreSQL database using Psycopg2. Here’s an example:

import psycopg2

# Connection details
conn = psycopg2.connect(
    host="your_host",
    database="your_database",
    user="your_user",
    password="your_password"
)

Replace the placeholders (your_host, your_database, your_user, your_password) with your actual connection details.

Calling a Stored Procedure

Once we have a connection, we can call a stored procedure using the callproc() method provided by Psycopg2.

Here’s an example of calling a stored procedure named get_product_count that accepts a category parameter and returns the count of products in that category:

# Execute the stored procedure with parameters
category = 'Electronics'
cursor = conn.cursor()
cursor.callproc('get_product_count', [category])
result = cursor.fetchone()[0]
cursor.close()
conn.close()

print(f"The count of products in the category {category} is: {result}")

Make sure to replace 'get_product_count' with the actual name of your stored procedure.

Conclusion

In this blog post, we learned how to call stored procedures using Psycopg2 in Python. We covered establishing a connection to the database and executing a stored procedure with parameters. Psycopg2’s callproc() method makes it easy to work with stored procedures in PostgreSQL.

If you’re working with PostgreSQL and need to execute complex operations, consider using stored procedures along with Psycopg2 to streamline your database operations.

Happy coding!