Handling a ResultSet
Recall the differences between a ResultProxy and a ResultSet:
- ResultProxy: The object returned by the
.execute()
method. It can be used in a variety of ways to get the data returned by the query. - ResultSet: The actual data asked for in the query when using a fetch method such as
.fetchall()
on a ResultProxy.
This separation between the ResultSet and ResultProxy allows us to fetch as much or as little data as we desire.
Once we have a ResultSet, we can use Python to access all the data within
it by column name and by list style indexes. For example, you can get the first
row of the results by using results[0]
. With that first row then assigned to a variable first_row
, you can get
data from the first column by either using first_row[0]
or by column name such
as first_row['column_name']
. You'll now practice exactly this using the ResultSet you obtained from the census
table in the previous exercise. It is stored in the variable results
. Enjoy!
This is a part of the course
“Introduction to Databases in Python”
Exercise instructions
- Extract the first row of
results
and assign it to the variablefirst_row
. - Print the value of the first column in
first_row
. - Print the value of the
'state'
column infirst_row
.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# 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(____)
This exercise is part of the course
Introduction to Databases in Python
In this course, you'll learn the basics of relational databases and how to interact with them.
In this chapter, you’ll get acquainted with the fundamentals of relational databases and the relational model for database management. You will learn how to connect to a database and interact with it by writing basic SQL queries, both in raw SQL as well as SQLAlchemy, which provides a Pythonic way of interacting with databases.
Exercise 1: Introduction to DatabasesExercise 2: Relational modelExercise 3: Connecting to your databaseExercise 4: Engines and connection stringsExercise 5: Autoloading Tables from a databaseExercise 6: Viewing Table detailsExercise 7: Introduction to SQL queriesExercise 8: Selecting data from a Table: raw SQLExercise 9: Selecting data from a Table with SQLAlchemyExercise 10: Handling a ResultSetExercise 11: Congratulations!What is DataCamp?
Learn the data skills you need online at your own pace—from non-coding essentials to data science and machine learning.