-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinit_db.py
More file actions
55 lines (48 loc) · 1.51 KB
/
init_db.py
File metadata and controls
55 lines (48 loc) · 1.51 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
import mysql.connector
from mysql.connector import errorcode
# MySQL连接配置
config = {
'user': 'soundbox',
'password': 'V1an1337',
'host': '127.0.0.1',
}
# 连接到MySQL
try:
cnx = mysql.connector.connect(**config)
cursor = cnx.cursor()
# 创建数据库
cursor.execute("CREATE DATABASE IF NOT EXISTS SoundboxBooking")
cursor.execute("USE SoundboxBooking")
# 删除User表(如果存在),然后创建User表
cursor.execute("DROP TABLE IF EXISTS User")
cursor.execute("""
CREATE TABLE User (
id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(8) NOT NULL,
token VARCHAR(128) DEFAULT NULL,
mailAddress VARCHAR(64) NOT NULL
)
""")
# 删除Booking表(如果存在),然后创建Booking表
cursor.execute("DROP TABLE IF EXISTS Booking")
cursor.execute("""
CREATE TABLE Booking (
id INT NOT NULL,
date DATE NOT NULL,
block INT NOT NULL,
status BOOL NOT NULL,
bookBy VARCHAR(8) DEFAULT NULL,
UNIQUE (id, date, block) -- 设置 (id, date, block) 组合为唯一
)
""")
print("数据库和表已成功创建。")
except mysql.connector.Error as err:
if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
print("用户名或密码错误。")
elif err.errno == errorcode.ER_BAD_DB_ERROR:
print("数据库不存在。")
else:
print(err)
finally:
cursor.close()
cnx.close()