python - How to escape a ' within a string? -


i have little script creates insert sql statement me.

for postgresql need wrap values inserted within 2 single quotes.

unfortunately of value strings inserted contain single quote, , need escape them automatically.

for line in f: out.write('(\'' + line[:2] + '\', \'' + line[3:-1] + '\'),\n') 

how can make sure single quote (e.g. ' ) inside line[3:-1] automatically escaped?

thanks,

update:

e.g. line

ci|cote d'ivoire 

fails due '

update 2:

i can't use double quotes in values, e.g.

insert "app_country" (country_code, country_name) values ("af", "afghanistan")

i error message: error: column "af" not exist

this works fine:

insert "app_country" (country_code, country_name) values ('af', 'afghanistan')

as described in pep-249, dbpi generic interface various databases. different implementations exist different databases. postgres there psycopg. docs:

cur.execute( ... """insert some_table (an_int, a_date, a_string) ... values (%s, %s, %s);""", ... (10, datetime.date(2005, 11, 18), "o'reilly")) 

you simple pass parameters in tuple. underlying library escapes you. safer , easier trying roll own.


Comments

Popular posts from this blog

javascript - backbone.js Collection.add() doesn't `construct` (`initialize`) an object -

php - Get uncommon values from two or more arrays -

Adding duplicate array rows in Php -