I'm attempting to insert data into a MySQL database through a Python script using parameterized queries rather than formatting the parameters into a string and opening the application up to SQL injection.
Here is the Python code:
#!/usr/bin/python3
import MySQLdb as mdb
conn = mdb.connect("localhost", "fakeuser", "fakepassword", "testdb")
c = conn.cursor()
c.execute("INSERT INTO test VALUES (%s)", ("Test", ))
conn.commit()
conn.close()
When I run the script, I get the following stack trace:
Traceback (most recent call last):
File "./load.py", line 7, in <module>
c.execute("INSERT INTO test VALUES (%s)", ("Test", ))
File "/opt/python3/lib/python3.2/site-packages/MySQL_python-1.2.3-py3.2-linux-x86_64.egg/MySQLdb/cursors.py", line 184, in execute
self.errorhandler(self, exc, value)
File "/opt/python3/lib/python3.2/site-packages/MySQL_python-1.2.3-py3.2-linux-x86_64.egg/MySQLdb/connections.py", line 37, in defaulterrorhandler
raise errorvalue
File "/opt/python3/lib/python3.2/site-packages/MySQL_python-1.2.3-py3.2-linux-x86_64.egg/MySQLdb/cursors.py", line 171, in execute
r = self._query(query)
File "/opt/python3/lib/python3.2/site-packages/MySQL_python-1.2.3-py3.2-linux-x86_64.egg/MySQLdb/cursors.py", line 330, in _query
rowcount = self._do_query(q)
File "/opt/python3/lib/python3.2/site-packages/MySQL_python-1.2.3-py3.2-linux-x86_64.egg/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)' at line 1")
However, every bit of documentation I've read suggests %s
is the correct placeholder. I've tried to enclose the %s
in single quotes, but that causes the statement to insert that string literally rather than substitute the given value, which is what I'd expect.
Here are the relevant software versions:
- Python 3.2.3
- MySQL_python-1.2.3-py3.2
- MySQL 5.5.40-36.1
Note: I'm using a shared host and cannot upgrade the software.