Python 模擬試験

Pythonデータ分析実践 模擬試験 第1回 問7・2章 データの種類と読み込み(データベース)

pandas から SQLite を読む

次のコードを実行したときの出力として、正しいものを1つ選べ。

import pandas as pd
import sqlite3
con = sqlite3.connect(":memory:")
con.execute("create table t (x integer)")
con.executemany("insert into t values (?)", [(1,), (2,), (3,)])
df = pd.read_sql("select sum(x) as s from t", con)
print(int(df["s"][0]))
  1. A

    3

  2. B

    1

  3. C

    6

  4. D

    sum(x)

正解と解説を見る

正解:C

pd.read_sql(SQL, 接続) で、SQL の実行結果を DataFrame に読み込める。

順実行する行実行後の変数
1`import pandas as pd`—
2`import sqlite3`—
3`con = sqlite3.connect(":memory:")`—
4`con.execute("create table t (x integer)")`—
5`con.executemany("insert into t values (?)", […`—
6`df = pd.read_sql("select sum(x) as s from t",…`df = DataFrame(1行×1列)
7`print(int(df["s"][0]))`df = DataFrame(1行×1列)
結果実際の出力6

学習のポイント:パラメータは、文字列連結ではなく、プレースホルダで渡す(SQL インジェクション対策)。

この問題を演習で解く →

問題一覧へ

このサイトの問題は、各試験の公式に示された出題範囲に沿って作ったオリジナルの模擬問題です。本試験の問題ではありません。一般社団法人Pythonエンジニア育成推進協会の公式サービスではありません。