Categories
Python Answers

How to insert multiple rows with one query with Python psycopg2?

Spread the love

Sometimes, we want to insert multiple rows with one query with Python psycopg2.

In this article, we’ll look at how to insert multiple rows with one query with Python psycopg2.

How to insert multiple rows with one query with Python psycopg2?

To insert multiple rows with one query with Python psycopg2, we can use the cursor mogrify method with the execute method.

For instance, we write

args_str = ','.join(cur.mogrify("(%s,%s,%s,%s,%s,%s,%s,%s,%s)", x) for x in tup)
cur.execute("INSERT INTO table VALUES " + args_str) 

to create the args_str string with the mogrify method that gets the values from the tup tuple and use them as values.

Then we concatenate that to the insert statement SQL string and call execute with the combined string.

Conclusion

To insert multiple rows with one query with Python psycopg2, we can use the cursor mogrify method with the execute method.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *