Postgresql how to convert insert value as parameters

Viewed 56

I have a insert sql:

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

I tired use parameters in query and pass the values separately:

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

Error:

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

any friend can help?

1 Answers

Try using executemany() here:

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

If you don't know a priori how many tuples to expect in the VALUES clause, then you may build it dynamically:

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)
Related