从表中过滤数据 - 基础
已连接数据库后,现在来练习如何对查询进行过滤!
正如视频中所述,where() 子句用于过滤语句返回的数据。例如,要从 census 表中选出性别为女性(即 'F')的所有记录,可以这样写:
select([census]).where(census.columns.sex == 'F')
除了 ==,在 where() 子句中基本可以使用任何 Python 比较运算符(例如 <=、
!= 等)。
本练习是课程的一部分
Python 中的数据库入门
练习说明
- 通过将
census作为列表传给select(),选取census表的全部记录。 - 给
stmt添加一个where子句,仅返回state为'New York'的记录。 - 在
connection上使用.execute()执行语句stmt,并用.fetchall()获取结果。 - 遍历
results,打印每条记录的age、sex和pop2000列。例如,您可以使用result.age打印result的age。
交互式实操练习
通过完成这段示例代码来试试这个练习。
# Create a select query: stmt
stmt = ____
# Add a where clause to filter the results to only those for New York : stmt_filtered
stmt = stmt.____
# Execute the query to retrieve all the data returned: results
results = ____
# Loop over the results and print the age, sex, and pop2000
for ___ in ____:
print(result.age, ____, ____)