删除多条SQL记录耗时过长的Python代码:如何优化?

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

我的

delete_ids
变量包含 8,000 个唯一的对话 ID。我试图循环地从我的 SQL 表中一次删除这 8,000 个对话 ID。我无法一次删除所有 8,000 个 ID,因为其中一些可能不是有效的会话 ID;它们可能是别的东西。因此,我编写了一个try-except块来跳过无法删除或导致错误的ID。然而,这个过程需要将近 40 分钟。我的
delete_ids
列表中的计数可能会有所不同,可能会上升或下降。有没有更有效的方法来提高我的代码的性能?

failed_deletions = []

if len(matching_records_sql) < len(matching_records_df):
    delete_ids = matching_records_sql['CONVERSATIONID'].tolist()
    if delete_ids: 
        delete_query = "DELETE FROM MY_TABLE WHERE CONVERSATIONID = ?"
        
        conn = pyodbc.connect(r'DRIVER={ODBC Driver 17 for SQL Server};'
                              r'SERVER=My_Server_Name;'
                              r'DATABASE=Database_Name;'
                              r'Trusted_Connection=yes;')
        cursor = conn.cursor()
        
        for id in delete_ids:
            try:
                cursor.execute(delete_query, (id,))
                conn.commit()
            except Exception as e:
                print(f"Failed to delete CONVERSATIONID {id}: {e}")
                failed_deletions.append(id)
        
        #conn.close()
        print('List of deleted ids from SQL table: ', [id for id in delete_ids if id not in failed_deletions])
        print('List of IDs that failed to delete: ', failed_deletions)
    else:
        print('No IDs to delete.')
else:
    print('matching_records_sql is not < matching_records_df')
python python-3.x pandas pyodbc
1个回答
0
投票

在这种情况下,您将单独执行 8000 次,并在每一次之后提交。这会生成 8000 个单独提交。

循环遍历 CONVERSATIONID 并适当过滤它们(检查约束或其他内容)的理想方式。此时你就知道哪个 CONVERSATIONID 会被删除或不被删除了。

然后您可以使用

DELETE FROM MY_TABLE WHERE CONVERSATIONID IN ?

一次性删除它们

此外,根据 FK 检查和索引,它可以改进您的查询,但只要从单个查询转移到聚合查询,您就应该看到巨大的性能改进。

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