Last active
December 11, 2020 03:22
-
-
Save AdamDimech/ace075ea5902014dc16a3087643d78ed to your computer and use it in GitHub Desktop.
Query a PostgreSQL database from Python. Further information at https://code.adonline.id.au/query-a-postgresql-database-via-python/
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
#!/usr/bin/env python | |
import psycopg2 | |
try: | |
login = "dbname='YourDatabaseName' user='Adam' host='127.0.0.1' " + \ | |
"password='MyPa$$word'" | |
# Establish a connection | |
conn = psycopg2.connect(login) | |
# Create a psycopg2 cursor that can execute queries | |
cursor = conn.cursor() | |
# Run a query | |
cursor.execute("""SELECT * from table""") | |
rows = cursor.fetchall() | |
print(rows) | |
cursor.close() | |
conn.close() | |
except Exception as e: | |
print("Unable to connect to database") | |
print(e) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment