Categories
Connecting to Data Stores Guides and Code Samples

Connecting to MySQL and MariaDB

Connecting to MySQL and MariaDB

Here’s a quick example of how to connect to MySQL as well as MariaDB using JetML workflows. 

Workflow Setup
  1. Add the pymysql package to enable Python to connect to MySQL. 
  2. Add your MySQL database credentials as environment variables to keep them separate than your code.
  3. Run the workflow.
  4. Copy over the example code below into a notebook on the running workflow. 
Example Notebook
				
					import logging
logger = logging.getLogger(__name__)
import pymysql
import os


def mysql_connection():

    host=os.environ['db_host']
    user=os.environ['db_user']
    password=os.environ['db_password']
    db=os.environ['database']

    conn = pymysql.connect(host=host, port=3306, user=user, passwd=password, db=db)

    return conn

def close_connection(cur,conn):

    cur.close()
    conn.close()

    return


sql = """
SELECT * from table
"""
conn = mysql_connection()

try:
    cur = conn.cursor()
    cur.execute(sql)
    conn.commit()
except:
    logger.error('error fetching table from db')
    raise ValueError('error fetching table from db')

row =cur.fetchone()
conn.commit()
logger.debug(row)
return row