【发布时间】:2018-06-19 23:22:42
【问题描述】:
我正在尝试编写一个将 dicts 列表插入到 postgres 中的函数,但我在处理引号时遇到了困难。
我有下面两个函数,一个是生成插入语句,一个是执行。
import psycopg2 as pg
import string
def create_insert_sql(record, table, on_key):
"""creates the sql insert statement"""
columns = list(record.keys())
insert_columns = ','.join([str(x) for x in columns])
columns.remove(on_key)
update_set = ','.join([str(x) for x in columns])
exclude_set = ','.join(['EXCLUDED.' + str(x) for x in columns])
values = ','.join(['\'' + str(x) + '\'' for x in record.values()])
insert_sql_statement = """
INSERT INTO {} ({})
VALUES ({})
ON CONFLICT ({})
DO UPDATE SET
({})
= ({}) ;
""".format(table, insert_columns, values, on_key, update_set, exclude_set)
return insert_sql_statement
def upsert_into_pg(dataset, table, on_key):
"""Given a list of dicts, upserts them into a table with on_key as conflict"""
conn = pg.connect(user=XXXX,
password=XXXX,
host='127.0.0.1',
port=3306,
database='XXXX')
cur = conn.cursor()
try:
for record in dataset:
cur.execute(create_insert_sql(record, table, on_key))
except Exception as e:
conn.rollback()
print(e)
else:
conn.commit()
print('upsert success')
finally:
cur.close()
conn.close()
错误示例
test = [
{'a': 'structure', 'b': 'l\'iv,id', 'c': 'doll', 'd': '42'},
{'a': '1', 'b': 'shoe', 'c': 'broke', 'd': '42'},
{'a': 'abc', 'b': 'proc', 'c': 'moe', 'd': '42'}
]
upsert_into_pg(test, 'testing', 'a')
返回
syntax error at or near "iv"
LINE 3: VALUES ('structure','l'iv,id','doll','42')
非常感谢任何帮助。
【问题讨论】:
-
如果使用参数对您不起作用(不了解 Python 中的数组),您可以将字符串文字中的所有单引号加倍。
-
而这个问题Insert text with single quotes in PostgreSQL有很多关于主题的答案
标签: python python-3.x postgresql psycopg2