什么是 Query?
在编程中,“Query”通常指对数据源(如数据库、API、文件或内存结构)发起的检索请求。在 Python 中,你可以使用多种方式执行 Query 操作,包括:
- 数据库查询(如 SQLite、MySQL、PostgreSQL)
- Web API 请求(如 RESTful 接口)
- 数据框(DataFrame)筛选(如 pandas)
- 列表/字典等结构的条件过滤
1. 数据库查询(SQLite 示例)
使用内置的 sqlite3 模块执行 SQL 查询:
import sqlite3
# 连接数据库
conn = sqlite3.connect('example.db')
cursor = conn.cursor()
# 执行查询
cursor.execute("SELECT name, age FROM users WHERE age > ?", (18,))
results = cursor.fetchall()
for row in results:
print(row)
conn.close()
2. Web API 查询(requests 库)
通过 HTTP 请求从远程服务获取数据:
import requests
# 发起 GET 请求并传递查询参数
params = {'q': 'python', 'sort': 'stars'}
response = requests.get('https://api.github.com/search/repositories', params=params)
if response.status_code == 200:
data = response.json()
for repo in data['items'][:3]:
print(repo['name'], repo['stargazers_count'])
3. 使用 Pandas 筛选数据
Pandas 提供了类似 SQL 的查询语法:
import pandas as pd
df = pd.read_csv('data.csv')
# 方法一:布尔索引
young_users = df[df['age'] < 30]
# 方法二:query() 方法(更接近 SQL)
result = df.query('age > 25 and city == "Beijing"')
print(result)
4. 列表与字典的条件查询
使用列表推导式或 filter() 实现内存数据筛选:
# 列表推导式
numbers = [1, 2, 3, 4, 5, 6]
evens = [n for n in numbers if n % 2 == 0]
# 字典查询
users = [{'name': 'Alice', 'age': 30}, {'name': 'Bob', 'age': 25}]
adults = [u for u in users if u['age'] >= 18]
# 使用 filter
high_scores = list(filter(lambda x: x > 90, [85, 92, 78, 96]))
最佳实践建议
- 始终对用户输入进行参数化处理,防止 SQL 注入。
- 使用 try-except 处理网络或数据库异常。
- 对于大型数据集,优先考虑向量化操作(如 pandas)而非循环。
- 合理使用缓存减少重复 Query 请求。