|
|
@ -0,0 +1,56 @@
|
|
|
|
|
|
|
|
# 教育机构 :山东科技大学
|
|
|
|
|
|
|
|
# 学生 :石廷达
|
|
|
|
|
|
|
|
# 开发日期 :2024/12/28
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
import pymysql
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
# 连接数据库的函数
|
|
|
|
|
|
|
|
def connect_db():
|
|
|
|
|
|
|
|
# 先连接 MySQL 的默认数据库(没有指定 db)
|
|
|
|
|
|
|
|
conn = pymysql.connect(
|
|
|
|
|
|
|
|
host="localhost",
|
|
|
|
|
|
|
|
port=3306,
|
|
|
|
|
|
|
|
user="root",
|
|
|
|
|
|
|
|
password="123456",
|
|
|
|
|
|
|
|
charset="utf8"
|
|
|
|
|
|
|
|
)
|
|
|
|
|
|
|
|
return conn
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
# 创建数据库的函数(如果数据库不存在)
|
|
|
|
|
|
|
|
def create_database_if_not_exists():
|
|
|
|
|
|
|
|
conn = connect_db()
|
|
|
|
|
|
|
|
cur = conn.cursor()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
# 检查数据库是否存在
|
|
|
|
|
|
|
|
cur.execute("SHOW DATABASES LIKE 'attendance_system'")
|
|
|
|
|
|
|
|
result = cur.fetchone()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
if result is None:
|
|
|
|
|
|
|
|
# 数据库不存在,创建数据库
|
|
|
|
|
|
|
|
cur.execute("CREATE DATABASE attendance_system")
|
|
|
|
|
|
|
|
print("Database 'attendance_system' created successfully.")
|
|
|
|
|
|
|
|
else:
|
|
|
|
|
|
|
|
print("Database 'attendance_system' already exists.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
# 关闭初始连接
|
|
|
|
|
|
|
|
conn.close()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
# 连接到特定的数据库
|
|
|
|
|
|
|
|
def connect_to_test_db():
|
|
|
|
|
|
|
|
conn = pymysql.connect(
|
|
|
|
|
|
|
|
host="localhost",
|
|
|
|
|
|
|
|
port=3306,
|
|
|
|
|
|
|
|
user="root",
|
|
|
|
|
|
|
|
password="123456",
|
|
|
|
|
|
|
|
db="attendance_system", # 使用新创建的数据库
|
|
|
|
|
|
|
|
charset="utf8"
|
|
|
|
|
|
|
|
)
|
|
|
|
|
|
|
|
return conn
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
create_database_if_not_exists() # 检查并创建数据库
|
|
|
|
|
|
|
|
conn = connect_to_test_db() # 连接到 `attendance_system` 数据库
|
|
|
|
|
|
|
|
cur = conn.cursor()
|