Escape backslash in Python parameterized MySQL query
<p>I am working on excel files and database storaging, precisely I am storaging excel data to MySQL database. At some point I am executing this query:</p>

<pre><code>query_for_id = ''' SELECT id FROM attivita WHERE attivita = '{0}' '''.format(attivita)
</code></pre>

<p>And when I print the query result I get this:</p>

<p>' SELECT id FROM attivita WHERE attivita = \\'Manutenzione\\' '</p>

<p>When it tries to match 'attivita' with the right value, taken from the excel, I got errors because of the '\\'.</p>

<p>I tried changing the triple quotes from " " " to ' ' ', as well as using <code>connection.escape_string()</code>, but I didn't solve the problem. Can anyone help me figuring out the problem? Thank you in advance.</p>

<p>I think that in your case better to use arguments to execute</p>

<pre><code>query_for_id = ''' SELECT id FROM attivita WHERE attivita = %(attivita)s '''
cursor.execute(query_for_id, { 'attivita': attivita })
</code></pre>

<p><a href="https://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursor-execute.html" rel="nofollow">https://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursor-execute.html</a></p>

python mysql sql