处理 ResultSet
回顾 ResultProxy 与 ResultSet 的区别:
- ResultProxy:由
.execute()方法返回的对象。它可以通过多种方式获取查询返回的数据。 - ResultSet:当在 ResultProxy 上使用
.fetchall()等提取方法时,查询实际返回的数据。
将 ResultSet 与 ResultProxy 分离,使我们可以按需提取任意多或任意少的数据。
一旦拿到 ResultSet,您可以用 Python 通过列名或列表式索引访问其中的所有数据。例如,您可以使用 results[0] 获取结果的第一行。将该第一行赋值给变量 first_row 后,您可以通过 first_row[0] 获取第一列的数据,或通过列名例如 first_row['column_name'] 来获取。现在,您将使用在上一个练习中从 census 表获得的 ResultSet 来练习这一点。它已存储在变量 results 中。开始吧!
本练习是课程的一部分
Python 中的数据库入门
练习说明
- 提取
results的第一行,并将其赋值给变量first_row。 - 打印
first_row中第一列的值。 - 打印
first_row中'state'列的值。
交互式实操练习
通过完成这段示例代码来试试这个练习。
# Get the first row of the results by using an index: first_row
first_row = ____
# Print the first row of the results
print(first_row)
# Print the first column of the first row by accessing it by its index
print(____)
# Print the 'state' column of the first row by using its name
print(____)