-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest.py
46 lines (38 loc) · 1.14 KB
/
test.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#!/usr/bin/env python3
import psycopg2
def main():
# Database connection parameters
host = "localhost"
port = 5433
dbname = "test"
user = "test"
password = "test"
try:
# Connect to the PostgreSQL database
conn = psycopg2.connect(
host=host,
port=port,
database=dbname,
user=user,
password=password
)
# List of tables to retrieve data from
tables = ["products"]
with conn.cursor() as cursor:
for table in tables:
print(f"\n--- Data from {table} ---")
# Retrieve all rows from the current table
cursor.execute(f"SELECT * FROM {table};")
rows = cursor.fetchall()
# Print the result set
for row in rows:
print(row)
except Exception as e:
print("An error occurred while connecting or fetching data:")
print(e)
finally:
# Ensure the connection is closed
if 'conn' in locals() and conn is not None:
conn.close()
if __name__ == "__main__":
main()