0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Python/SQLインジェクション対策

Posted at

・コードでSQL文を生成する際に、文字列をそのまま受け取り条件分として使用しない様注意する

※プレースホルダを使用しない場合の書き方

入力値のhoge=['111111','2222222'...]があるとして
この値をそのままWHERE句の条件に設定するのはNG

よくない例

hoge = ['111111', '22222222']
query = "SELECT * FROM testTable WHERE id IN ({});".format(
    ",".join(f"'{h}'" for h in hoge)
)
print(query)

出力結果

SELECT * FROM testTable WHERE id IN ('111111','22222222');

SQLインジェクションを考慮した安全な例(おそらく)


hoge = ['111111', '22222222']
query = "SELECT * FROM testTable WHERE id IN ({});".format(
    ",".join(str(int(h)) for h in hoge)
)
print(query)


出力結果

SELECT * FROM testTable WHERE id IN (111111,22222222);

strで受け取り、intに変換することで不正な文字列であればValueErrorで
落ちる為、不正なクエリ文の入力を弾くことができる

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?