如何从SQLite数据库Budget.db直接读取数据填充Python列表
实现方法
你可以根据实际需求选择以下两种方案,无需再手动硬编码维护地点列表。
方案1:全量读取数据库数据生成列表(推荐)
直接查询Locations表的所有Name字段值生成列表,完全替换原有硬编码内容,后续只需要维护数据库中的地点数据即可,无需修改代码。
实现代码:
import sqlite3 # 建立数据库连接 connection = sqlite3.connect('C:/Users/Administrator/project/BUDGET.db') cursor = connection.cursor() # 查询所有地点数据 cursor.execute("SELECT Name FROM Locations") # 提取结果生成和原有格式一致的字符串列表 locationList = [row[0] for row in cursor.fetchall()] # 操作完成后关闭游标和连接 cursor.close() connection.close()
方案2:将数据库数据追加到现有硬编码列表
如果需要保留原有手动录入的列表内容,再补充数据库中存储的所有地点,可以使用列表追加的方式实现:
import sqlite3 connection = sqlite3.connect('C:/Users/Administrator/project/BUDGET.db') cursor = connection.cursor() # 保留原有硬编码列表 locationList = [ 'Aberdeen; Aberdeen Airport', 'Belfast; Belfast International Airport Aldergrove', 'Belfast; George Best Belfast City Airport', 'Birmingham; Terminal Building', 'Blackpool; Blackpool Airport', 'Bristol; Bristol Airport', 'Cardiff; Meet And Greet Only', 'Edinburgh; Car Rental Centre', 'Exeter; Exeter Airport', 'Glasgow; Glasgow International Airport', ] # 读取数据库中的地点 cursor.execute("SELECT Name FROM Locations") db_locations = [row[0] for row in cursor.fetchall()] # 将数据库数据追加到现有列表 locationList.extend(db_locations) # 若需要去除重复内容(避免硬编码数据和数据库数据重复),Python3.7+可使用以下保序去重代码 # locationList = list(dict.fromkeys(locationList)) cursor.close() connection.close()
注意:sqlite3的
fetchall()方法返回的是元组列表,每个元素为(字段值,)格式,必须通过row[0]提取第一个元素,才能得到符合要求的字符串列表。
内容的提问来源于stack exchange,提问作者Kishen
相关产品推荐
相关产品推荐

