2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Python MySQLdb で Prepared Statement がうまくいかない場合

Last updated at Posted at 2019-01-06

こんなエラーが出てうまくいかない場合

  File "/root/.local/lib/python3.5/site-packages/MySQLdb/cursors.py", line 184, in execute
    self.errorhandler(self, exc, value)
  File "/root/.local/lib/python3.5/site-packages/MySQLdb/connections.py", line 37, in defaulterrorhandler
    raise errorvalue
  File "/root/.local/lib/python3.5/site-packages/MySQLdb/cursors.py", line 171, in execute
    r = self._query(query)
  File "/root/.local/lib/python3.5/site-packages/MySQLdb/cursors.py", line 330, in _query
    rowcount = self._do_query(q)
  File "/root/.local/lib/python3.5/site-packages/MySQLdb/cursors.py", line 294, in _do_query
    db.query(q)
_mysql_exceptions.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 \'%s, "%s")\' at line 1')

Qiitaの記事とか参考にしてもなぜかうまくいかない。多分こちらの環境設定とかが問題。
実行環境は Cent OS 6.9 Python 3.5.2 MySQL 5.6.42
似たような現象の人もいるようで、、、別のやり方の個人メモです。
https://stackoverflow.com/questions/32116909/python-mysqldb-typeerror-with-formatting-problems
https://www.pythonanywhere.com/forums/topic/2857/
https://www.pythonanywhere.com/forums/topic/1825/
https://github.com/kennethreitz/records/issues/166

mysql-connector-python を代わりに使う

# pip install mysql-connector-python

mysql-connector-python で 同様にPrepared Statement を利用する

import mysql.connector

connection = mysql.connector.MySQLConnection(host='localhost',
                             database=DB_NAME,
                             user=DB_USER,
                             password=DB_USER_PASSWORD)
cursor = connection.cursor(prepared=True)

sql = 'INSERT INTO test_table (id, content) VALUES (%s, %s)'
data = (1,"A")
cursor.execute(statement, data)
connection.commit()

dataset = [
  (2, "B"),
  (3, "C"),
  (4, "D"),
]
cursor.executemany("INSERT INTO test_table (id, content) VALUES (%s, %s)",dataset)
connection.commit()

カーソルを作る時に「prepared=True」を忘れないようにすればMySQLdbと同じようにできます。

2
2
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
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?