代码之家  ›  专栏  ›  技术社区  ›  William

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

  •  1
  • William  · 技术社区  · 3 年前

    我有一个insert 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)
    

    有朋友能帮忙吗?

    1 回复  |  直到 3 年前
        1
  •  2
  •   Tim Biegeleisen    3 年前

    试用 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)