Python mysql.connector module, Passing data into string VALUES %s
<p>I'm having trouble passing data into %s token. I've looked around and noticed that this Mysql module handles the %s token differently, and that it should be escaped for security reasons, my code is throwing this error. </p>

<p>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</p>

<p>If I do it like this: </p>

<pre><code>sql_insert = ("INSERT INTO `Products` (title) VALUES(%s)"),(data)
</code></pre>

<p>I get a tuple error.. </p>

<pre><code>import mysql.connector
from mysql.connector import errorcode

cnx = mysql.connector.connect (user='userDB1', password='UserPwd1',
host='somedatabase.com', database='mydatabase1')
cursor = cnx.cursor()

sql_insert = ("INSERT INTO `Products` (title) VALUES(%s)")

data=('HelloSQLWORLD')

cursor.execute(sql_insert,data)

cnx.commit()


cnx.close()
</code></pre>

<p>No, don't do it the way @Jeon suggested - by using string formatting you are exposing your code to <a href="https://en.wikipedia.org/wiki/SQL_injection" rel="nofollow">SQL injection attacks</a>. Instead, <em>properly parameterize the query</em>:</p>

<pre><code>query = """
    INSERT INTO 
        Products 
        (title) 
    VALUES
        (%s)"""

cursor.execute(query, ('HelloSQLWORLD', ))
</code></pre>

<p>Note how the query parameters are put into a <em>tuple</em>.</p>

python mysql