Documentation Index
Fetch the complete documentation index at: https://mintlify.com/HotCode2025/Print-Estoy-Cansado-Jefe-TercerSemestre/llms.txt
Use this file to discover all available pages before exploring further.
psycopg2 is the most widely used PostgreSQL adapter for Python. It implements the DB-API 2.0 specification and gives you a clean, Pythonic interface to open connections, execute SQL, and retrieve results. Whether you are building a small script or a production-grade API, psycopg2 is the de-facto standard for talking to PostgreSQL from Python.
Installing psycopg2
Install the package from PyPI before writing any connection code:If you run into binary dependency errors on Linux, install the standalone binary wheel instead:
Creating a Connection
Usepsycopg2.connect() and pass your database credentials as keyword arguments. The example below uses the test_bd database running on localhost:
connection.py
Never hardcode passwords in production code. Store sensitive credentials in
environment variables and read them with
os.getenv('DB_PASSWORD'). This
keeps secrets out of version control and makes your code portable across
environments.Creating a Cursor and Executing a SELECT Query
Once you have a connection object, create a cursor — the object you use to send SQL statements to the database and retrieve results:cursor_fetchall.py
cursor.execute() sends the SQL to the server. The results are not automatically downloaded — you must call a fetch method to pull them into Python.
fetchone() vs fetchall()
psycopg2 offers two primary fetch methods. Choose the one that fits the expected result size:| Method | Returns | Best used when |
|---|---|---|
fetchone() | A single tuple, or None | You expect exactly one row (e.g., lookup by primary key) |
fetchall() | A list of tuples | You need all matching rows at once |
Closing the Connection
Always release the connection and cursor when you are done. There are two ways to do this:with statement as a context manager on the cursor ensures it is closed automatically when the block exits, even if an exception is raised. The outer try / finally guarantees the connection is always closed.
Note that
with conexion: (the connection as a context manager) controls the
transaction, not the connection lifetime. You still need to call
conexion.close() explicitly in the finally block to return the connection
to the operating system. See the
psycopg2 usage docs for full
details.