Discuss / Python / 作业

作业

Topic source

greatzues

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

不太熟悉数据库查询的语法,得到数据方式有点low,别介意

#!/usr/bin/env/ python3
#-*- coding:utf-8 -*-

import os, sqlite3

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

try:
    conn = sqlite3.connect(db_file)
    cursor = conn.cursor()
    cursor.execute('create table user(id varchar(20) primary key, name varchar(20),score int)')
    cursor.execute(r"insert into user values ('A-1001','Adam', 95)")
    cursor.execute(r"insert into user values ('A-1002','Bart', 62)")
    cursor.execute(r"insert into user values ('A-1003','Lisa', 78)")
except Exception as e:
    print('Error:',e)
finally:
    cursor.close()
    conn.commit()
    conn.close()

def get_score_in(low, high):
    try:
        conn = sqlite3.connect(db_file)
        cursor = conn.cursor()
        list = []
        for i in range(low, high+1):
            cursor.execute('select * from user where score=?',(i,))
            values = cursor.fetchall()
            if values == []:
                continue
            else:
                list.append(values[0][1])
    except Exception as e:
        print('Error:',e)
    finally:
        cursor.close()
        conn.close()
    return list

# 测试:
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')

  • 1

Reply