Skip to content

Instantly share code, notes, and snippets.

@AdamDimech
Last active December 11, 2020 03:22
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 AdamDimech/ace075ea5902014dc16a3087643d78ed to your computer and use it in GitHub Desktop.
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/
#!/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