Postgresql 如何纠正使用python3在postgres表中多次插入时的错误?
我用于将多条记录插入postgresql的python 3代码如下: 忽略以下代码中必要的初始化变量,“cur”是游标对象,“conn”是db连接对象:Postgresql 如何纠正使用python3在postgres表中多次插入时的错误?,postgresql,python-3.6,Postgresql,Python 3.6,我用于将多条记录插入postgresql的python 3代码如下: 忽略以下代码中必要的初始化变量,“cur”是游标对象,“conn”是db连接对象: sql = """INSERT INTO logs( mfrom, mto,mstatus, mstatus_string) VALUES(%s, %s, %s, %s)""" row_d
sql = """INSERT INTO logs(
mfrom, mto,mstatus, mstatus_string)
VALUES(%s, %s, %s, %s)"""
row_dict = {
"mfrom": mfrom,
"mto": mto,
"mstatus": mstatus,
"mstatus_string": mstatus_string
}
mtup = tuple(row_dict.values())
list1.append(mtup)
val_str = ','.join(cur.mogrify('(%s,%s,%s,%s)', x).decode('utf-8') for x in list1)
try:
cur.execute(sql, val_str)
conn.commit()
time.sleep(0.1)
list1 = []
except Exception as e:
conn.rollback()
print(e, 'Error')
我得到的错误是:
字符串格式化错误期间未转换所有参数
通过对sql、val_str和cur.execute语句进行如下更改来解决:
sql = """INSERT INTO logs(
mfrom, mto,mstatus, mstatus_string)
VALUES """
val_str = ','.join(cur.mogrify("(%s,%s,%s,%s)", x).decode(
'utf-8') for x in list1)
cur.execute(sql + val_str)