综合练习:成绩管理

56.13 综合练习:成绩管理

综合运用:建表 → 插入 → 查询 → 统计 → 更新 → 删除。

建议独立完成后再对照代码;可扩展为命令行菜单程序。

迷你成绩管理器

可在此基础上加 input 菜单:1添加 2查询 3排行榜 4退出。

import sqlite3

def init_db():
    with sqlite3.connect('school.db') as conn:
        conn.execute('''CREATE TABLE IF NOT EXISTS students (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            name TEXT NOT NULL UNIQUE,
            score REAL
        )''')

def add_student(name, score):
    with sqlite3.connect('school.db') as conn:
        conn.execute('INSERT INTO students(name,score) VALUES (?,?)', (name, score))

def list_top(n=5):
    with sqlite3.connect('school.db') as conn:
        conn.row_factory = sqlite3.Row
        cur = conn.execute(
            'SELECT name, score FROM students ORDER BY score DESC LIMIT ?', (n,)
        )
        return [dict(r) for r in cur]

init_db()
add_student('张三', 92)
add_student('李四', 85)
for s in list_top():
    print(s['name'], s['score'])