Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

format single quote in SQL statement

Tags:

python

My question is simple, in Python, How do I format a SQL statement that contains single quotes in it?

I have a place name

"Musee d'Orsay"

What I want is

"Musee d\'Orsay"

so, I tried replace single quote by using following statement

str.replace("'","\'")

but, it return the original string. Can you give me any help?

double slash worked well.

str.replace("'","\\'")


OK, Thanks for all response. I have figured it out.

I must escape it by doubling the single quote.

str.replace("'","''")

INSERT INTO table_name VALUES (Musee d''Orsay);

It works for me.

like image 880
Stephen Avatar asked Apr 10 '26 08:04

Stephen


1 Answers

Your should not create sql queries by preparing the string that will go in it : you sould use placeholders and let the library doing the escaping work for you.

That exact syntax may change depending on the database you use. For example, in sqlite :

m = "Musée d'Orsay"
cursor.execute('SELECT * FROM table WHERE museum=?', m)
like image 188
madjar Avatar answered Apr 13 '26 01:04

madjar