Skip to content

Instantly share code, notes, and snippets.

@oldarmyc
Created December 10, 2018 18:23
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 oldarmyc/78c8c753bf8630e31bf58cc7ce1f268b to your computer and use it in GitHub Desktop.
Save oldarmyc/78c8c753bf8630e31bf58cc7ce1f268b to your computer and use it in GitHub Desktop.
MariaDB example connection
"""
To connect to mariadb you would need to conda install the mysql-connector-python package
conda install -c anaconda mysql-connector-python
"""
import mysql.connector as mariadb
import json
# Read the credentials from secret
credentials = None
with open('/var/run/secrets/user_credentials/mariadb_credentials') as f:
credentials = json.load(f)
# Ensure your credentials were setup
if credentials:
# Connect to the DB
connection = mariadb.connect(
user=credentials.get('user'),
password=credentials.get('password'),
database=credentials.get('database'),
host=credentials.get('host')
)
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}')
# Close the connection
connection.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment