Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python mySQL - escaping quotes

I have seen this question asked in various ways on this website, but none of them exactly addressed my issue.

I have an sql statement with single quotes inside it, and am trying to use recommended practices before making database queries with it. So the statement is like

val2="abc 'dostuff'" 
sql="INSERT INTO TABLE_A(COL_A,COL_B) VALUES(%s,'%s')" %(val1, val2)
a_cursor.execute(sql)

However, when I run this, I get..

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 'dostuff'.

What am I doing wrong? Thanks very much Nupur

like image 808
Nupur Avatar asked Oct 15 '12 19:10

Nupur


People also ask

How do I escape a single quote in MySQL?

Similarly, we can use backslash to escape single quotes and double quotes to insert values into MySQL table.

How to escape single and double quotes in MySQL?

If you need to use single quotes and double quotes in a string that contains both a contraction and a quote, you will need to use the backslash '' to cancel out the following character.

Why does MySQL use Backticks?

Backticks ( ` ) are used to indicate database, table, and column names. Unless you're using reserved or conflicting words for table and database names, you'll not need to use them. Quotes ( ' or " ) are used to delimit strings, and differentiate them from column names.

How do you escape a single quote from a string in Python?

You can put a backslash character followed by a quote ( \" or \' ). This is called an escape sequence and Python will remove the backslash, and put just the quote in the string. Here is an example.


1 Answers

Use parameters instead of string interpolation to ensure that your values are properly escaped by the database connector:

sql = "INSERT INTO TABLE_A(COL_A,COL_B) VALUES(%s, %s)"
a_cursor.execute(sql, (val1, val2))

The mysqldb sql parameter style uses the same syntax as used by the python string formatting operator, which is a little confusing.

like image 139
Martijn Pieters Avatar answered Sep 21 '22 18:09

Martijn Pieters