Postgresql如何将插入值转换为参数

Postgresql how to convert insert value as parameters

我有一个插页sql:

cur.execute(f"""INSERT INTO patients_patient (patient_id, patient_name) VALUES
                      (1,'Jane'),(2,'John')""")

我厌倦了在查询中使用参数并分别传递值:

cur.execute(f"""INSERT INTO patients_patient (patient_id, patient_name) VALUES
                      (%s,%s),(%s,%s)""",(1,'Jane'),(2,'John'))

错误:

cur.execute(f"""INSERT INTO patients_patient (patient_id, patient_name) VALUES
TypeError: function takes at most 2 arguments (3 given)

有朋友可以帮忙吗?

尝试在此处使用 executemany()

sql = 'INSERT INTO patients_patient (patient_id, patient_name) VALUES (?, ?)'
values = [(1, 'Jane'), (2, 'John')]
cur.executemany(sql, values)

如果您事先不知道 VALUES 子句中有多少元组,那么您可以动态构建它:

sql = 'INSERT INTO patients_patient (patient_id, patient_name) VALUES '
values = [(1, 'Jane'), (2, 'John')]
sql += '(%s' + ',%s'*(len(values)-1) + ')'
cur.executemany(sql, values)