I'm new to mysql, python and the mysql Python connector. Wanting to learn best-practice. I have an initialization method to create the db, create the tables and/or populate it with data (depending upon what's missing).
When cursor gets overwritten does it cleanup any resources anyway? Could something be done better?
def initialize(config):
connection = None
cursor = None
# open the database connection
try:
connection = mysql.connector.connect(**config["DATABASE"]["CONNECTION"])
cursor = connection.cursor()
except mysql.connector.Error as err:
print(err)
exit(1)
# connection successful, check if the db exists already
name = config["DATABASE"]["NAME"]
try:
cursor.execute("USE {}".format(name))
except mysql.connector.Error as err:
print("Database {} does not exist".format(name))
if err.errno == errorcode.ER_BAD_DB_ERROR:
print("Creating {}...".format(name))
try:
cursor.execute(
"CREATE DATABASE {} DEFAULT CHARACTER SET 'utf8mb4'".format(name)
)
except mysql.connector.Error as err:
print("Failed creating database: {}".format(err))
exit(1)
print("Database {} created successfully".format(name))
# set the active database
connection.database = name
else:
print(err)
exit(1)
# also set connection to use the new database
config["DATABASE"]["CONNECTION"]["database"] = config["DATABASE"]["NAME"]
# load and run schema
# safe to do as it doesn't create tables if they exist
with open(config["DATABASE"]["SCHEMA"], "rb") as f:
tables = f.read().decode("utf-8").split(";")
for table in tables:
table = re.sub("[\n\r]", "", table)
if len(table) > 0:
try:
cursor.execute(table)
connection.commit()
except mysql.connector.Error as err:
print(err)
exit(1)
# if there is test data
if config["DATABASE"]["DATA"] != "":
# if the db is empty
cursor.execute("SELECT * FROM account LIMIT 1")
# must fetch the data for the cursor
cursor.fetchone()
if cursor.rowcount == 0:
# populate
with open(config["DATABASE"]["DATA"], "rb") as f:
tables = f.read().decode("utf-8").split(";")
for table in tables:
table = re.sub("[\n\r]", "", table)
if len(table) > 0:
try:
cursor.execute(table)
connection.commit()
except mysql.connector.Error as err:
print(err)
exit(1)
# cleanup
cursor.close()
connection.close()