I have written this code that connects to a mysql database. The function should be able to be used as a context manager - via with
. It is working, but I am not sure if this is a great way of doing it.
conect.py
import os
import mysql.connector
from mysql.connector import errorcode
import contextlib
_CFG = {
'user': os.getenv("MYSQL_USER"),
'password': os.getenv("MYSQL_PASSWORD"),
'host': os.getenv("MYSQL_SERVER"),
'database': os.getenv("SENSOR_DB"),
'raise_on_warnings': True
}
@contextlib.contextmanager
def _connect(db=None):
if db:
_CFG["database"] = db
try:
print("{usr} connecting to {db} on {host}.".format(
usr=_CFG["user"],
db=_CFG["database"],
host=_CFG["host"]
)
)
connection = mysql.connector.connect(**_CFG)
yield connection
except mysql.connector.Error as err:
if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
print("Something is wrong with your user name or password")
elif err.errno == errorcode.ER_BAD_DB_ERROR:
print("Database does not exist")
else:
print(err)
yield None
else:
connection.commit()
finally:
connection.close()