Created
June 26, 2023 14:58
-
-
Save d-kahara/d2e5868949f063a87ca941d00fa89301 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import psycopg2 | |
def get_data(): | |
try: | |
# Establish a connection to the database | |
connection = psycopg2.connect( | |
user = "your_username", | |
password = "your_password", | |
host = "127.0.0.1", # replace with your host if different | |
port = "5432", # replace with your port if different | |
database = "your_database" | |
) | |
# Create a cursor object | |
cursor = connection.cursor() | |
# SQL query to execute | |
query = "YOUR_SQL_QUERY" # replace with your SQL query | |
# Execute the SQL query | |
cursor.execute(query) | |
# Fetch all the rows | |
rows = cursor.fetchall() | |
for row in rows: | |
print(row) | |
except (Exception, psycopg2.Error) as error: | |
print("Error while fetching data from PostgreSQL", error) | |
finally: | |
# Close the database connection | |
if (connection): | |
cursor.close() | |
connection.close() | |
print("PostgreSQL connection is closed") | |
get_data() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment