プレースホルダ付き SQL
次のコードを実行したときの出力として、正しいものを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,)])
print(pd.read_sql("select x from t where x > ?", con, params=(1,))["x"].tolist())
- A
[2, 3] - B
[1, 2, 3] - C
[1] - D
[]
正解と解説を見る
正解:A
SQL に値を渡すときは、文字列の連結ではなく、プレースホルダと params を使う。SQL インジェクションを防げる。
| 順 | 実行する行 | 実行後の変数 |
|---|---|---|
| 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 | `print(pd.read_sql("select x from t where x > …` | — |
| 結果 | 実際の出力 | [2, 3] |
- A
正しい。プレースホルダ
?にparamsの値を渡して、x > 1の行を取り出す。 - B
誤り。条件で絞り込まれる。
- C
誤り。
x > 1の行。 - D
誤り。2 と 3 が条件に合う。
このサイトの問題は、各試験の公式に示された出題範囲に沿って作ったオリジナルの模擬問題です。本試験の問題ではありません。一般社団法人Pythonエンジニア育成推進協会の公式サービスではありません。