Discuss / Python / SQLite

SQLite

Topic source

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

import os, sqlite3

# os.path.dirname(file)返回文件目录 db_file = os.path.join(os.path.dirname(file), 'test.db') # 若表存在则删除 if os.path.isfile(db_file): os.remove(db_file)

# 初始数据: 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-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)") cursor.close() conn.commit() conn.close()

def get_score_in(low, high): conn1 = sqlite3.connect(db_file) cursor1 = conn1.cursor() cursor1.execute('select name from user where score >= ? and score <= ? order by score',(low,high)) values = cursor1.fetchall() cursor1.close() conn1.close() print('fetchall()返回的原始数据:%s' % values) values = list(map(lambda x:x[0],values)) print('查询列表如下:%s' % values) return values

# 测试: assert get_score_in(80, 96) == ['Adam'], get_score_in(80, 96) 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