我正在尝试通过python(psycopg2)在postgres中进行插入。我需要在执行插入的字符串中包含单引号和双引号。 这是我的代码:
table_name = "my_table"
values_to_insert = ["""O'neal""", '''"The Film "''']
column_name_list = ["UpperAndLowercase", "otherColumn"]
"INSERT INTO {} ".format(table_name) + ", ".join(['''"{}"'''.format(i) for i in
column_name_list]) + " VALUES(" + ", ".join("""'''{}'''"""
.format(i).encode("utf-8").decode('unicode_escape') for i in values_to_insert)
我希望如此:
'INSERT INTO my_table "UpperAndLowercase", "otherColumn" VALUES('''O'neal''', '''"The Film "''''
但是得到这个:
'INSERT INTO my_table "UpperAndLowercase", "otherColumn" VALUES(\'\'\'O\'neal\'\'\', \'\'\'"The Film "\'\'\''
答案 0 :(得分:0)
您是否正在使用python解释器?请注意下面x与x(x)的外观。
如果我将您的代码放在脚本中并打印出来,对我来说看起来不错。
>>> table_name = "my_table"
>>> values_to_insert = ["""O'neal""", '''"The Film "''']
>>> column_name_list = ["UpperAndLowercase", "otherColumn"]
>>>
>>> x = "INSERT INTO {} ".format(table_name) + ", ".join(['''"{}"'''.format(i) for i in
... column_name_list]) + " VALUES(" + ", ".join("""'''{}'''"""
... .format(i).encode("utf-8").decode('unicode_escape') for i in values_to_insert)
>>> x
'INSERT INTO my_table "UpperAndLowercase", "otherColumn" VALUES(\'\'\'O\'neal\'\'\', \'\'\'"The Film "\'\'\''
>>> print(x)
INSERT INTO my_table "UpperAndLowercase", "otherColumn" VALUES('''O'neal''', '''"The Film "'''
>>>
请注意,您可以只使用三元组"""
而不是'''
s = """ this has 'single' and "double" quotes """
答案 1 :(得分:0)
您可以大大简化代码:
table_name = "my_table"
values_to_insert = ["O'neal", '"The Film "']
column_name_list = ["UpperAndLowercase", "otherColumn"]
print "INSERT INTO {} ".format(table_name) + ", ".join(['"{}"'.format(i) for i in column_name_list]) + " VALUES(" + ", ".join(["'''{}'''".format(i) for i in values_to_insert])
输出您想要的结果:
INSERT INTO my_table "UpperAndLowercase", "otherColumn" VALUES('''O'neal''', '''"The Film "'''