%s place holder does not let me insert ' in an sql query with python.
Bruno Desthuilliers
bdesth.quelquechose at free.quelquepart.fr
Mon Dec 15 16:27:27 EST 2008
Joe Strout a écrit :
> 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.)
Or just learn to make proper use of the db-api, ie use
cursor.execute(
"select yadda from mytable where foo=%s or bar=%s",
(foo, bar)
)
NB : replace '%s' with '?' or whatever is the correct placeholder for
you particular db-api connector.
More information about the Python-list
mailing list