Here is my code:
import csv import mysql.connector
mydb = mysql.connector.connect( host="localhost", user="root", passwd="root", database="4g_hs_upgrade" )
mycursor = mydb.cursor()
sql = "INSERT INTO test (num) VALUES %s"
val = 'John'
mycursor.execute(sql, (val))
mydb.commit()
Here is the error I'm getting :
Traceback (most recent call last): File "csvreader.py", line 13, in mycursor.execute(sql, (val)) File "/usr/lib/python2.7/dist-packages/mysql/connector/cursor.py", line 507, in execute self._handle_result(self._connection.cmd_query(stmt)) File "/usr/lib/python2.7/dist-packages/mysql/connector/connection.py", line 722, in cmd_query result = self._handle_result(self._send_cmd(ServerCmd.QUERY, query)) File "/usr/lib/python2.7/dist-packages/mysql/connector/connection.py", line 640, in _handle_result raise errors.get_exception(packet) mysql.connector.errors.ProgrammingError: 1064 (42000): 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
%sin the string, but the string isn't followed by a%and an expression to substitute something for the string? See here pyformat.info for a more modern and Pythonic way to do things. And keep in mind that in the current version of python you can also writef'some {x} string'to format it withx, instead of'some {} string'.format(x).(val, )to make it a tuple; note that(val) == valbecause parentheses are interpreted as arithmetic grouping, e.g.1 + (2 + 3) + 4. On the other hand,(1, )makes a tuple, just like(1, 2, ) == (1, 2).