Discuss / Python / 交作业

交作业

Topic source

苏生不语_

#1 Created at ... [Delete] [Delete and Lock User]
# -*- coding: utf-8 -*-
import os
import sqlite3
from contextlib import contextmanager

db_file = os.path.join(os.path.dirname('.'), 'test.db')
if os.path.isfile(db_file):
    os.remove(db_file)


@contextmanager
def get_cursor_sqlite3(db_f):
    conn = sqlite3.connect(db_f)
    cursor = conn.cursor()
    yield cursor
    # 测试时发现 出现异常时rowcount的值为-1
    if cursor.rowcount > 0:
        conn.commit()
    cursor.close()
    conn.close()


# 初始数据:
try:
    with get_cursor_sqlite3(db_file) as cursor:
        cursor.execute('create table user(id varchar(20) primary key, name varchar(20), score int)')
        cursor.execute(r"insert into user values ('A-001', 'Adam', 95)")
        cursor.execute(r"insert into user values ('A-002', 'Bart', 62)")
        cursor.execute(r"insert into user values ('A-003', 'Lisa', 78)")
except Exception as e:
    print(e)


def get_score_in(low, high):
    # ' 返回指定分数区间的名字,按分数从低到高排序 '
    try:
        with get_cursor_sqlite3(db_file) as cursor:
            cursor.execute('select name from user where score between ? and ? order by score', (low, high))
            values = cursor.fetchall()
            names = list(map(lambda x: x[0], values))
            print(names)
    except Exception as e:
        print(e)
    return names


# 测试:
assert get_score_in(80, 95) == ['Adam'], get_score_in(80, 95)
assert get_score_in(60, 80) == ['Bart', 'Lisa'], get_score_in(60, 80)
assert get_score_in(60, 100) == ['Bart', 'Lisa', 'Adam'], get_score_in(60, 100)

print('Pass')

Champhy_Who

#2 Created at ... [Delete] [Delete and Lock User]

厉害


  • 1

Reply