import psycopg2
# Step 1: Connect to the PostgreSQL database
try:
connection = psycopg2.connect(
host="localhost", # Database host
port="5432", # Port (default for PostgreSQL)
database="postgres", # Your database name
user="username", # Your PostgreSQL username
password="password" # Your PostgreSQL password
)
# Step 2: Create a cursor object to interact with the database
cursor = connection.cursor()
# Step 3: Write a query to fetch rows from a table
query = "SELECT * FROM test1.user1;" # Replace with your table name
# Step 4: Execute the query
cursor.execute(query)
# Step 5: Fetch all rows from the executed query
rows = cursor.fetchall()
# Step 6: Display the rows
print("Fetched rows:")
for row in rows:
print(row)
except Exception as error:
print("Error while fetching data from PostgreSQL", error)
finally:
# Step 7: Close the cursor and connection
if cursor:
cursor.close()
if connection:
connection.close()