Created
December 10, 2018 18:28
-
-
Save oldarmyc/8127da210f1c2d22eb5ac27cfbfe234e to your computer and use it in GitHub Desktop.
MySQL example connection
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
""" | |
To connect to mysql you would need to conda install the mysql-connector-python conda package | |
conda install -c anaconda mysql-connector-python | |
""" | |
import mysql.connector as mysql | |
import json | |
# Get credentials from kubernetes. The credentials were setup as a dictionary | |
credentials = None | |
with open('/var/run/secrets/user_credentials/mysql_credentials') as f: | |
credentials = json.load(f) | |
if credentials: | |
# Connect to the DB | |
connection = mysql.connect( | |
user=credentials.get('username'), | |
password=credentials.get('password'), | |
database='employees', | |
host='support-mysql.dev.anaconda.com' | |
) | |
cursor = connection.cursor() | |
# Execute the query | |
cursor.execute("SELECT first_name, last_name FROM employees LIMIT 20") | |
# Loop through the results | |
for first_name, last_name in cursor: | |
print(f'First name: {first_name}, Last name: {last_name}') | |
connection.close() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment