Skip to content

Instantly share code, notes, and snippets.

@ShaikeA
Last active January 17, 2019 19:43
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 ShaikeA/913235de19bf8ec5fbea72d4ef850f10 to your computer and use it in GitHub Desktop.
Save ShaikeA/913235de19bf8ec5fbea72d4ef850f10 to your computer and use it in GitHub Desktop.
import mysql.connector
def build_database(db_name, host_name, user_name, password, all_sql_tables):
# Define the connection and the cursor that is used for executing the SQL commands
my_db = mysql.connector.connect(host=host_name, user=user_name, passwd=password, database=db_name)
cursor = my_db.cursor()
# Execute all SQL commands and commit it into the DB
for sql_q in all_sql_tables:
cursor.execute(sql_q)
my_db.commit()
logger.info("\n*** Database was created successfully. ***\n") # log into a logs file
# If we get an error at some point, the my_db.rollback() reverts everything to the state we had in our last commit
except mysql.connector.Error as error:
my_db.rollback() # rollback if any exception occured
logger.critical("Failed creating database {}.".format(error)) # log into a logs file
# Close database connection no matter what happened before
finally:
if my_db is not None and my_db.is_connected():
cursor.close() ; my_db.close()
logger.info("MySQL connection is closed.")
else:
logger.info("connection to MySQL did not succeed.")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment