如果你还没有安装 MySQL,请先安装 MySQL Server(如 MySQL 8.0),并创建一个数据库。
🗃️ 第二步:创建数据库和表
登录 MySQL 命令行或使用 MySQL Workbench,执行以下 SQL:
sql
创建数据库
CREATE DATABASE IF NOT EXISTS school_db CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
使用数据库
USE school_db;
创建学生表
CREATE TABLE students (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(50) NOT NULL,
age INT CHECK (age = 0 AND age <= 150),
email VARCHAR(100) UNIQUE,
enrollment_date DATE DEFAULT (CURDATE())
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
def add_student(name, age, email):
添加学生
conn = get_db_connection()
if not conn:
return False
try:
with conn.cursor() as cursor:
sql = INSERT INTO students (name, age, email) VALUES (%s, %s, %s)
cursor.execute(sql, (name, age, email))
conn.commit()
print(f✅ 学生 {name} 添加成功!ID: {cursor.lastrowid})
return True
except pymysql.IntegrityError as e:
print(f❌ 添加失败:邮箱 {email} 已存在或数据无效。)
return False
except Exception as e:
print(f❌ 发生错误:{e})
return False
finally:
conn.close()
def view_all_students():
查看所有学生
conn = get_db_connection()
if not conn:
return
try:
with conn.cursor() as cursor:
sql = SELECT * FROM students ORDER BY id
cursor.execute(sql)
students = cursor.fetchall()
if not students:
print(❌ 暂无学生信息。)
return
print(\n📋 所有学生信息:)
print(- * 60)
for s in students:
print(fID: {s['id']} | 姓名: {s['name']:10} | 年龄: {s['age']:3} | 邮箱: {s['email']:20} | 入学时间: {s['enrollment_date']})
except Exception as e:
print(f❌ 查询失败:{e})
finally:
conn.close()
def update_student(student_id, name=None, age=None, email=None):
更新学生信息(可选字段)
conn = get_db_connection()
if not conn:
return False
try:
with conn.cursor() as cursor:
updates = []
params = []
if name is not None:
updates.append(name = %s)
params.append(name)
if age is not None:
updates.append(age = %s)
params.append(age)
if email is not None:
updates.append(email = %s)
params.append(email)
if not updates:
print(⚠️ 没有提供需要更新的字段。)
return False
sql = fUPDATE students SET {', '.join(updates)} WHERE id = %s
params.append(student_id)
cursor.execute(sql, params)
conn.commit()
if cursor.rowcount 0:
print(f✅ 学生 ID {student_id} 更新成功!)
return True
else:
print(f❌ 未找到 ID 为 {student_id} 的学生。)
return False
except pymysql.IntegrityError:
print(❌ 更新失败:邮箱已存在。)
return False
except Exception as e:
print(f❌ 更新出错:{e})
return False
finally:
conn.close()
def delete_student(student_id):
删除学生
conn = get_db_connection()
if not conn:
return False
try:
with conn.cursor() as cursor:
sql = DELETE FROM students WHERE id = %s
cursor.execute(sql, (student_id,))
conn.commit()
if cursor.rowcount 0:
print(f✅ 学生 ID {student_id} 已删除。)
return True
else:
print(f❌ 未找到 ID 为 {student_id} 的学生。)
return False
except Exception as e:
print(f❌ 删除失败:{e})
return False
finally:
conn.close()