From c392d1772d974f0f3b8e3c0f7b21dd83e64f2827 Mon Sep 17 00:00:00 2001 From: Fred Z Date: Fri, 27 Jul 2018 18:46:33 +0200 Subject: [PATCH] Creates DB if not exist #4 --- db.py | 68 ++++++++++++++++++++++++++++++++++++++++------------------- 1 file changed, 46 insertions(+), 22 deletions(-) diff --git a/db.py b/db.py index 18572ec..7374344 100644 --- a/db.py +++ b/db.py @@ -11,54 +11,78 @@ Connect to DB import pymysql.cursors +# CONFIG CONFIG = { 'host': 'localhost', 'user': 'loff', 'pass': 'loff', 'db': 'loff', - 'char': 'utf8' + 'char': 'utf8', + 'file': 'create-db-loff.sl' } +DB_NOT_FOUND = True +# FUNCTION +def sql_create_db(filename=CONFIG['file']): + """ + Get the SQL instruction to create the DB for file + + :return: a list of each SQL query whithout the trailing ";" + """ + from os import path + + # Loading file + if path.isfile(filename) is False: + print("File load error : {}".format(filename)) + return False + + else: + with open(filename, "r") as sql_file: + # Split file in list + ret = sql_file.read().split(';') + # drop last empty entry + ret.pop() + return ret + + +# WORK # Connect to the database -connection = pymysql.connect(host=CONFIG['host'], +CONNECTION = pymysql.connect(host=CONFIG['host'], user=CONFIG['user'], password=CONFIG['pass'], - database=CONFIG['db'], charset=CONFIG['char'], cursorclass=pymysql.cursors.DictCursor) try: - with connection.cursor() as cursor: + with CONNECTION.cursor() as cursor: # Show DB cursor.execute("SHOW DATABASES") - db_list = cursor.fetchall() + db_list = cursor.fetchall() - for line in range(len(db_list)): + for idx, val in enumerate(db_list): - if CONFIG['db'] in db_list[line].values(): - # DB found + if CONFIG['db'] in db_list[idx].values(): + DB_NOT_FOUND = False cursor.execute("USE {}".format(CONFIG['db'])) + print('DB exist : ready to use it.') - # else: - # Create DB - # cursor.execute(create_db) + # No DB, create it + if DB_NOT_FOUND: + request_list = sql_create_db() + + if request_list is not False: + + for idx, sql_request in enumerate(request_list): + # print(sql_request + ';') + print("-- REQUEST #{} : --{}".format(idx, sql_request)) + cursor.execute(sql_request + ';') except pymysql.err.OperationalError as except_detail: print("DB error: «{}»".format(except_detail)) finally: - connection.close() - -def function(): - """ - Function documentation - - :Tests: - >>> a = 10 - >>> a + 5 - 15 - """ + CONNECTION.close() if __name__ == "__main__":