一、核心需求
使用 Python 创建一个本地 SQLite 数据库,生成学生成绩表,并写入 1000 条模拟学生数据。该脚本适合用于 SQL 查询练习,例如成绩排名、平均分统计、不及格筛选、按年龄分组分析等。
数据库文件保存位置:
data/student.db核心脚本文件:
init_student_db.py二、脚本结构
脚本主要分为 4 个部分:
创建数据库连接
重建学生表
生成并插入模拟数据
执行初始化流程
整体流程如下:
创建 data 目录
↓
连接 data/student.db
↓
删除旧 students 表
↓
创建新 students 表
↓
生成 1000 条学生成绩数据
↓
批量写入数据库三、核心代码
1. 数据库路径配置
from pathlib import Path
BASE_DIR = Path(__file__).resolve().parent
DATA_DIR = BASE_DIR / "data"
DB_PATH = DATA_DIR / "student.db"说明:
BASE_DIR表示当前脚本所在目录。DATA_DIR表示数据库文件夹。DB_PATH表示最终生成的 SQLite 数据库文件。
使用 Path 管理路径,可以避免手动拼接字符串导致路径错误。
2. 创建数据库连接
import sqlite3
def create_conn() -> sqlite3.Connection:
"""创建数据库连接"""
DATA_DIR.mkdir(exist_ok=True)
return sqlite3.connect(DB_PATH)说明:
DATA_DIR.mkdir(exist_ok=True)用于保证data目录存在。sqlite3.connect(DB_PATH)用于连接 SQLite 数据库。如果数据库文件不存在,SQLite 会自动创建。
3. 创建学生表
def reset_student_table(conn: sqlite3.Connection) -> None:
"""重建学生表"""
conn.execute("DROP TABLE IF EXISTS students")
conn.execute(
"""
CREATE TABLE students (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
age INTEGER NOT NULL,
math INTEGER NOT NULL,
english INTEGER NOT NULL,
history INTEGER NOT NULL,
total INTEGER NOT NULL
)
"""
)字段说明:
id 学生编号,自增主键
name 学生姓名
age 年龄
math 数学成绩
english 英语成绩
history 历史成绩
total 总分DROP TABLE IF EXISTS 适合练习场景,每次运行脚本都会得到一份干净的数据。
4. 批量插入学生数据
import random
def set_student_data(conn: sqlite3.Connection) -> None:
"""设置学生数据"""
students = []
for student in range(1000):
age = random.randint(14, 18)
math = random.randint(0, 100)
english = random.randint(0, 100)
history = random.randint(0, 100)
total = math + english + history
students.append((f"student_{student}", age, math, english, history, total))
conn.executemany(
"""
INSERT INTO students (name, age, math, english, history, total)
VALUES (?, ?, ?, ?, ?, ?)
""",
students,
)
conn.commit()说明:
random.randint(14, 18)随机生成年龄。random.randint(0, 100)随机生成各科成绩。total = math + english + history计算总分。executemany()用于一次性插入多条数据。conn.commit()用于提交事务,保证数据真正写入数据库。
四、运行方式
在项目根目录执行:
python init_student_db.py运行完成后,会生成数据库文件:
data/student.db五、可练习的 SQL
查询总分前 10 名:
SELECT name, age, math, english, history, total
FROM students
ORDER BY total DESC
LIMIT 10;统计各科平均分:
SELECT
ROUND(AVG(math), 2) AS avg_math,
ROUND(AVG(english), 2) AS avg_english,
ROUND(AVG(history), 2) AS avg_history
FROM students;筛选任意一科不及格的学生:
SELECT name, math, english, history
FROM students
WHERE math < 60 OR english < 60 OR history < 60;按年龄统计人数和平均总分:
SELECT
age,
COUNT(*) AS student_count,
ROUND(AVG(total), 2) AS avg_total
FROM students
GROUP BY age
ORDER BY age;六、脚本做了什么
使用
Path生成稳定的数据库路径。使用
sqlite3连接本地数据库文件。使用 SQL 创建
students表。使用
random生成模拟学生成绩。使用
executemany()批量插入 1000 条数据。使用
commit()提交事务。
Tips
如果后续需要固定每次生成的数据,可以在生成数据前设置随机种子:
random.seed(2026)如果需要保留旧数据,不要执行:
DROP TABLE IF EXISTS students;
评论区