Created
December 10, 2018 18:19
-
-
Save oldarmyc/6eb688b9c7fec9c4be135b1e2e820413 to your computer and use it in GitHub Desktop.
PostgreSQL example connection
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
""" | |
Package psycopg2 must be installed through conda for this to work | |
conda install -c anaconda psycopg2 | |
""" | |
import psycopg2 | |
import json | |
# Get credentials from kubernetes. The credentials were setup as a dictionary | |
credentials = None | |
with open('/var/run/secrets/user_credentials/postgres_credentials') as f: | |
credentials = json.load(f) | |
# Check and make sure the credentials were pulled correctly | |
if credentials: | |
# Connect to the database | |
conn = None | |
try: | |
conn = psycopg2.connect( | |
dbname=credentials.get('db_name'), | |
host=credentials.get('host_name'), | |
user=credentials.get('username'), | |
password=credentials.get('password') | |
) | |
except: | |
print("I am unable to connect to the database") | |
# Get a cursor and execute select statement | |
cur = conn.cursor() | |
cur.execute("""SELECT * from playground""") | |
rows = cur.fetchall() | |
# Print out the results | |
for row in rows: | |
print(row) | |
# Close the connection when finished | |
conn.close() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment