Created
February 20, 2021 14:44
-
-
Save devashishpatil56/c048f9b2bb1511961bc4a5f770d78ab5 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 os | |
import psycopg2 | |
from psycopg2 import Error | |
import psycopg2.extras | |
from psycopg2.extras import RealDictCursor | |
try: | |
# connect to the database | |
connection = psycopg2.connect(host=os.environ['db_endpoint'], | |
user=os.environ['db_username'], | |
password=os.environ['db_password'], | |
dbname=os.environ['db_name'], | |
connect_timeout=30 | |
) | |
cursor = connection.cursor(cursor_factory=RealDictCursor) # create the cursor | |
table_name = "exmaple_table" | |
sql = "SELECT * FROM {}".format(table_name) # Write SQL query | |
cursor.execute(query) # Execute the query | |
connection.commit() # Commit the changes | |
result = cursor.fetchall() # you can use cursor.fetchone() to fetch the top row | |
cursor.close() # close the cursor | |
except (Exception, psycopg2.Error) as e: | |
print("Error in running the query: {}".format(str(e))) | |
finally: | |
connection.close() | |
print("Database connection closed") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment