# mysqlclientのプレースホルダでIN句を使う

- URL: https://www.blog.danishi.net/2020/06/04/post-3678/
- 公開日: 2020-06-04
- 更新日: 2025-07-18
- 著者: danishi
- カテゴリー: 調べてみた
- タグ: MySQL, SQL, Python
- この記事には広告（アフィリエイトリンク）が含まれています。

PythonのmysqlclientでIN句を使う方法を調べました。

```python {filename="sql_where_in.py"}
import MySQLdb

connection = MySQLdb.connect(
    host='localhost',
    user='root',
    passwd='',
    db='mydatabase',
    charset='utf8'
)
cursor = connection.cursor()

try:
    sqlstr = '''
SELECT
    id
   ,name
  FROM mytable
WHERE
'''
    ids = ['1', '3']
    format_strings = ','.join(['%s'] * len(ids))
    where_string = " id IN(%s)" % format_strings
    sqlstr = sqlstr + where_string

    cursor.execute(sqlstr, ids)
    print(cursor._executed.decode('utf-8'))

    print('-------------')
    for row in cursor.fetchall():
        print(row)

except MySQLdb.Error as e:
    print(e)
```

```console
python sql_where_in.py

SELECT
    id
   ,name
  FROM mytable
WHERE
 id IN('1','3')
-------------
(1, 'taro')
(3, 'jiro')
```

クエリ文字列を組み立てるときに、フォーマット文字列にIN句に入れる配列分フォーマット文字列を入れて、配列をバインドしています。

---

[ゲームセンターあらしと学ぶ プログラミング入門 まんが版こんにちはPython](https://www.amazon.co.jp/dp/B0872TNKDW?tag=danishi0a-22)（Amazon、PR）
