Blog

cursor.executemany(operation, seq_of_params) の挙動

python の cursor.executemany(operation, seq_of_params) について、

data = [
  ('Jane', date(2005, 2, 12)),
  ('Joe', date(2006, 5, 23)),
  ('John', date(2010, 10, 3)),
]
stmt = "INSERT INTO employees (first_name, hire_date) VALUES (%s, %s)"
cursor.executemany(stmt, data)

みたいなケースでは、いい感じに

INSERT INTO employees (first_name, hire_date)
VALUES ('Jane', '2005-02-12'), ('Joe', '2006-05-23'), ('John', '2010-10-03')

のようなクエリが実行される。

この機構は以下のような regexp にマッチした場合にのみ動作する、とのこと。

restr = r"""
    \s
    values
    \s*
    (
        \(
            [^()']*
            (?:
                (?:
                        (?:\(
                            # ( - editor hightlighting helper
                            .*
                        \))
                    |
                        '
                            [^\\']*
                            (?:\\.[^\\']*)*
                        '
                )
                [^()']*
            )*
        \)
    )
"""

https://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursor-executemany.html