开始使用免费开始使用

从表中过滤数据 - 基础

已连接数据库后,现在来练习如何对查询进行过滤!

正如视频中所述,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,打印每条记录的 agesexpop2000 列。例如,您可以使用 result.age 打印 resultage

交互式实操练习

通过完成这段示例代码来试试这个练习。

# 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, ____, ____)
编辑并运行代码