Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Postgresql how to convert insert value as parameters

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading