Home  >  Article  >  Backend Development  >  How Can Psycopg2\'s `mogrify` Method Speed Up Multiple Row Inserts?

How Can Psycopg2\'s `mogrify` Method Speed Up Multiple Row Inserts?

DDD
DDDOriginal
2024-11-25 03:32:15167browse

How Can Psycopg2's `mogrify` Method Speed Up Multiple Row Inserts?

Efficiently Inserting Multiple Rows with Psycopg2

Psycopg2 offers a mogrify method that can simplify the task of inserting multiple rows into a database with a single query. This approach can prove more efficient than using the executemany method, especially for large datasets.

To illustrate, the following code snippet demonstrates how to insert 2000 rows into a table:

args = [(1, 2), (3, 4), (5, 6)]
args_str = ','.join(cur.mogrify("(%s,%s)", x) for x in tup)
cur.execute("INSERT INTO table VALUES " + args_str)

This method proved to be significantly faster than using executemany in this specific scenario, taking only 10 seconds compared to 2 minutes. The mogrify method in psycopg2 prepares a query string for each row, avoiding the need to iterate over the list of rows multiple times as required by the executemany method.

The above is the detailed content of How Can Psycopg2\'s `mogrify` Method Speed Up Multiple Row Inserts?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn