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(____)