Creates DB if not exist #4
This commit is contained in:
parent
80ace05a4a
commit
c392d1772d
68
db.py
68
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__":
|
||||
|
|
Loading…
Reference in New Issue