Skip to content

Instantly share code, notes, and snippets.

@d-kahara
Created June 26, 2023 14:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save d-kahara/d2e5868949f063a87ca941d00fa89301 to your computer and use it in GitHub Desktop.
Save d-kahara/d2e5868949f063a87ca941d00fa89301 to your computer and use it in GitHub Desktop.
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