psycopg2 - 插入多行更快的列

问题描述 投票:0回答:2

我正在尝试在我的数据库中插入多行,目前我不知道同时插入所有行的方法或任何其他有助于节省时间的方法(顺序大约300行需要大约30秒)。

我的'行'是元组列表中的元组(转换为元组元组),例如[(col0, col1, col2), (col0, col1, col2), (.., .., ..), ..]

def commit(self, tuple):
    cursor = self.conn.cursor()
    for tup in tuple:
        try:
            sql = """insert into "SSENSE_Output" ("productID", "brand", "categoryID", "productName", "price", "sizeInfo", "SKU", "URL", "dateInserted", "dateUpdated")
              values (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)"""

            cursor.execute(sql, tup)
            self.conn.commit()
        except psycopg2.IntegrityError:
            self.conn.rollback()
            sql = 'insert into "SSENSE_Output" ' \
                  '("productID", "brand", "categoryID", "productName", "price", "sizeInfo", "SKU", "URL", "dateInserted", "dateUpdated")' \
                  'values (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s) on conflict ("productID") do update set "dateUpdated" = EXCLUDED."dateUpdated"'
            cursor.execute(sql, tup)
            self.conn.commit()
        except Exception as e:
            print(e)

在for循环完成后我也尝试了提交,但仍然会产生相同的时间。有没有办法让这个插入速度明显加快?

python postgresql tuples psycopg2
2个回答
0
投票

构建一个大的INSERT语句而不是其中许多将大大改善执行时间,你应该看看here。它适用于mysql,但我认为类似的方法适用于postgreSQL


0
投票

在postgres中,您可以使用以下格式:

INSERT INTO films (code, title, did, date_prod, kind) VALUES
('B6717', 'Tampopo', 110, '1985-02-10', 'Comedy'),
('HG120', 'The Dinner Game', 140, DEFAULT, 'Comedy');

由于您的记录基础异常处理,您可以在生成此查询之前首先解决重复项,因为发生完整性错误时整个查询可能会失败。

© www.soinside.com 2019 - 2024. All rights reserved.