我有一个小脚本,它为我创建一个特定的INSERT SQL语句。
对于postgresql,我需要将要插入的值封装在两个单引号中。
不幸的是,要插入的一些值字符串也包含一个单引号,我需要自动转义它们。
for line in f:
out.write('(\'' + line[:2] + '\', \'' + line[3:-1] + '\'),\n')如何确保line[3:-1]中的任何单引号(例如‘)自动转义?
谢谢,
更新:
这条线
CI|Cote D'ivoire未到期“
更新2:
我不能在值中使用双引号。
INSERT INTO "App_country" (country_code, country_name) VALUES ("AF", "Afghanistan")
我收到错误消息:ERROR: column "AF" does not exist
不过,这样做很好:
INSERT INTO "App_country" (country_code, country_name) VALUES ('AF', 'Afghanistan')
发布于 2012-07-06 23:40:43
发布于 2012-07-07 00:04:13
逃避引用的SQL标准方法是将其加倍:
'This won''t be a problem.'因此,将每个引号替换为两个引号(并在Python中使用双引号以保持理智):
out.write("('" + line[:2] + "', '" + line[3:-1].replace("'", "''") + "'),\n")发布于 2012-07-07 00:32:09
不要对DML使用生成的、滚动的自己的转义。使用基思提到的适当的DBAPI。为了确保从各种源和类型转换几乎可以透明地发生,工作已经开始了。如果您正在使用DDL (如CREATE TABLE whatever (...) )--如果您信任您自己的数据源,您可能会稍微松懈一些。
使用示例中显示的数据的
import sqlite3
text = "CI|Cote D'ivoire" # had to been escaped as it's a string literal, but from another data source - possibly not...
code, name = text.split('|', 1)
db = sqlite3.connect(':memory:')
db.execute('create table something(code, name)')
db.execute('insert into something(code, name) values(?, ?)', (code, name))
for row in db.execute('select * from something'):
print row
# (u'CI', u"Cote D'ivoire")https://stackoverflow.com/questions/11370594
复制相似问题