%s place holder does not let me insert ' in an sql query with python.

Joe Strout joe at strout.net
Mon Dec 15 10:29:37 EST 2008


On Dec 15, 2008, at 6:46 AM, Krishnakant wrote:

> in this case, I get a problem when there is ' in any of the values
> during insert or update.

That's because ' is the SQL string literal delimiter.  But any SQL- 
compliant database allows you to "escape" an apostrophe within a  
string literal by doubling it.  So for each of your values, just do:

   value = value.replace("'", "''")

before stuffing them into your INSERT or UPDATE statement.  (If these  
values come from the user, and especially if they come over the  
network, then you probably want to do a few other replacements; google  
"SQL injection" for details.)

Note that I'm not familiar with the cursor.execute binding that RDM  
pointed out, so that may provide a better solution... but the above  
should work.

Best,
- Joe




More information about the Python-list mailing list