LoginSignup
1
0

More than 3 years have passed since last update.

MYSQLdbのexecuteメソッドに文字列を代入する時の注意点

Posted at

メモ帳がわりの記事

python側のコードから直接SQLを書いてMySQLに投げる時の注意点

これはエラーにならない

hoge = 1
cursor.execute("""
            SELECT 〜いろんなカラム〜
            FROM てーぶる名
            WHERE カラム1=%s
            ;
        """, (hoge,))

これはエラーになる

hoge = ' IN (0, 1)'
cursor.execute("""
            SELECT 〜いろんなカラム〜
            FROM てーぶる名
            WHERE カラム1%s
            ;
        """, (hoge,))

下記のようなエラーが表示される。改行コード\nが含まれている。
文字列が入ると改行コードも含まれてしまうようになる?
(よくわからないので、詳しい人は教えていただきたい

django.db.utils.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''=1 '\n            AND latitude IS NOT NULL\n            AND カラム1 IS NOT NULL' at line 4")

なので下記のようにするとよい。
重要なポイントは先にquery文を変数に格納することだそうです。 (query = f"""のところ)


        hantei = True
        hoge = ' IN (0, 1)' if hantei else ' =1 '

        query = f"""
            SELECT いろんなカラム
            FROM テーブル名
            WHERE カラム1{hoge};
        """

        cursor.execute(query)

文字列を入れると改行コードを急に含むようになるとか、その辺り良い感じにやってほしい(文句)
この記事と関係ないけどf''''''はとても便利

1
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
1
0