Menu Close

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

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.

Posted in Python, Python Answers