侧边栏壁纸
博主头像
前端学习

行动起来,活在当下

  • 累计撰写 314 篇文章
  • 累计创建 18 个标签
  • 累计收到 0 条评论

目 录CONTENT

文章目录

Python + SQLite 学生成绩数据库初始化练习

Administrator
2026-06-18 / 0 评论 / 0 点赞 / 0 阅读 / 0 字

一、核心需求

使用 Python 创建一个本地 SQLite 数据库,生成学生成绩表,并写入 1000 条模拟学生数据。该脚本适合用于 SQL 查询练习,例如成绩排名、平均分统计、不及格筛选、按年龄分组分析等。

数据库文件保存位置:

data/student.db

核心脚本文件:

init_student_db.py

二、脚本结构

脚本主要分为 4 个部分:

  1. 创建数据库连接

  2. 重建学生表

  3. 生成并插入模拟数据

  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"

说明:

  1. BASE_DIR 表示当前脚本所在目录。

  2. DATA_DIR 表示数据库文件夹。

  3. DB_PATH 表示最终生成的 SQLite 数据库文件。

使用 Path 管理路径,可以避免手动拼接字符串导致路径错误。

2. 创建数据库连接

import sqlite3

def create_conn() -> sqlite3.Connection:
    """创建数据库连接"""
    DATA_DIR.mkdir(exist_ok=True)
    return sqlite3.connect(DB_PATH)

说明:

  1. DATA_DIR.mkdir(exist_ok=True) 用于保证 data 目录存在。

  2. sqlite3.connect(DB_PATH) 用于连接 SQLite 数据库。

  3. 如果数据库文件不存在,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()

说明:

  1. random.randint(14, 18) 随机生成年龄。

  2. random.randint(0, 100) 随机生成各科成绩。

  3. total = math + english + history 计算总分。

  4. executemany() 用于一次性插入多条数据。

  5. 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;

六、脚本做了什么

  1. 使用 Path 生成稳定的数据库路径。

  2. 使用 sqlite3 连接本地数据库文件。

  3. 使用 SQL 创建 students 表。

  4. 使用 random 生成模拟学生成绩。

  5. 使用 executemany() 批量插入 1000 条数据。

  6. 使用 commit() 提交事务。

Tips

如果后续需要固定每次生成的数据,可以在生成数据前设置随机种子:

random.seed(2026)

如果需要保留旧数据,不要执行:

DROP TABLE IF EXISTS students;

0

评论区