The psycopg2 library is a Python adapter for PostgreSQL, and it is commonly used for database interactions in Python applications. By default, psycopg2 fetches a single row from the database when you execute a query. To fetch multiple rows, you need to specify the desired fetch method.

Here's how you can fetch multiple rows using psycopg2:

python
import psycopg2 # Replace these with your actual database credentials db_params = { 'host': 'your_host', 'database': 'your_database', 'user': 'your_username', 'password': 'your_password' } def fetch_multiple_rows(): try: connection = psycopg2.connect(**db_params) cursor = connection.cursor() query = "SELECT * FROM your_table;" cursor.execute(query) # Use fetchall() to get all rows returned by the query rows = cursor.fetchall() # Process the rows as needed for row in rows: print(row) cursor.close() connection.close() except psycopg2.Error as e: print("Error connecting to the database:", e) fetch_multiple_rows()

In the code above, the fetchall() method is used to retrieve all rows returned by the query. This method returns a list of tuples, where each tuple represents a row from the database.

If you want to fetch a specific number of rows at a time, you can use the fetchmany(size) method, which fetches the next size number of rows. For example:

python
# ... def fetch_multiple_rows(): try: connection = psycopg2.connect(**db_params) cursor = connection.cursor() query = "SELECT * FROM your_table;" cursor.execute(query) # Fetch 10 rows at a time rows = cursor.fetchmany(10) # Process the rows as needed while rows: for row in rows: print(row) rows = cursor.fetchmany(10) cursor.close() connection.close() except psycopg2.Error as e: print("Error connecting to the database:", e) fetch_multiple_rows()

In this example, the fetchmany(10) method fetches 10 rows at a time until there are no more rows returned by the query.

Remember to adjust the query and the database credentials in the db_params dictionary to match your specific database and query requirements.

Have questions or queries?
Get in Touch