-
Notifications
You must be signed in to change notification settings - Fork 35
Expand file tree
/
Copy pathcreate_mysql_db.py
More file actions
74 lines (55 loc) · 1.7 KB
/
Copy pathcreate_mysql_db.py
File metadata and controls
74 lines (55 loc) · 1.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
#!/usr/bin/env python3
import argparse
import pymysql
import conf
def connect_server():
return pymysql.connect(
host=conf.DB_HOST,
user=conf.DB_USER,
passwd=conf.DB_PASS,
charset="utf8mb4",
autocommit=True,
)
def database_exists(connection, db_name):
with connection.cursor() as cursor:
cursor.execute("SHOW DATABASES LIKE %s", (db_name,))
return cursor.fetchone() is not None
def create_database(connection, db_name):
with connection.cursor() as cursor:
cursor.execute(
"""
CREATE DATABASE IF NOT EXISTS `{db_name}`
CHARACTER SET utf8mb4
COLLATE utf8mb4_unicode_ci
""".format(db_name=db_name)
)
cursor.execute(
"ALTER DATABASE `{db_name}` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci".format(
db_name=db_name
)
)
def drop_database(connection, db_name):
with connection.cursor() as cursor:
cursor.execute("DROP DATABASE IF EXISTS `{db_name}`".format(db_name=db_name))
def ensure_database(db_name, recreate=False):
connection = connect_server()
try:
if recreate:
drop_database(connection, db_name)
create_database(connection, db_name)
finally:
connection.close()
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument(
"--recreate",
action="store_true",
help="Drop the configured database before creating it.",
)
return parser.parse_args()
def main():
args = parse_args()
ensure_database(conf.DB_NAME, recreate=args.recreate)
print(conf.DB_NAME)
if __name__ == "__main__":
main()