From b346cf8c96807e3eeae9b24a7cb611f0447e1647 Mon Sep 17 00:00:00 2001 From: m5tqol2ew Date: Sun, 29 Dec 2024 15:51:27 +0800 Subject: [PATCH] =?UTF-8?q?=E5=AE=9E=E7=8E=B0=E8=BF=9E=E6=8E=A5=E6=95=B0?= =?UTF-8?q?=E6=8D=AE=E5=BA=93=E7=9A=84=E5=8A=9F=E8=83=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- conn.py | 56 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 conn.py diff --git a/conn.py b/conn.py new file mode 100644 index 0000000..f367dbb --- /dev/null +++ b/conn.py @@ -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()