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!