こんなエラーが出てうまくいかない場合
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と同じようにできます。