To read data from a PostgreSQL database using Python, you can use the psycopg2
library. Here’s an example code
import psycopg2 # Connect to the PostgreSQL database conn = psycopg2.connect( host='your_host', user='your_user', password='your_password', database='your_database' ) # Create a cursor object cur = conn.cursor() # Execute a SELECT query query = "SELECT * FROM your_table" cur.execute(query) # Fetch all rows from the result set rows = cur.fetchall() # Iterate over the rows and print each row for row in rows: print(row) # Close the cursor and connection cur.close() conn.close()
In this example, replace 'your_host'
, 'your_user'
, 'your_password'
, and 'your_database'
with the actual connection details for your PostgreSQL database.
The code establishes a connection to the PostgreSQL database using the specified host, username, password, and database name. It then creates a cursor object to execute SQL queries.
The example executes a SELECT query on the specified table ('your_table'
) and fetches all the rows from the result set using the fetchall()
method. It then iterates over the rows and prints each row.
Finally, the cursor and connection are closed to release the resources.
Make sure to have the psycopg2
library installed before running this code. You can install it using pip:
pip install psycopg2
Remember to handle any exceptions that may occur during the database connection or query execution for proper error handling.