通过python脚本缓慢插入,即使只有400行

2024-06-16 11:42:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个400行的“数据帧”。你知道吗

当我尝试将数据推送到sqlserver(在azurevm上)时,插入大约需要4分钟。你知道吗

下面是我使用的exceutemany语句:

cursor.executemany(insert_query,df)

我知道cursor.executemany是逐行插入的,但是对于400行来说,花4分钟就有点奇怪了。你知道吗

你能帮我解决这个问题吗?你知道吗


Tags: 数据df语句querycursorinsertsqlserverexecutemany
1条回答
网友
1楼 · 发布于 2024-06-16 11:42:26

请参考本文件Pyodbc Cursor`。 你可以executemany(sql, *params), with fast_executemany=True。你知道吗

对整个参数集执行SQL语句,不返回任何参数。单个params参数必须是序列序列或序列生成器。你知道吗

params = [ ('A', 1), ('B', 2) ]
cursor.fast_executemany = True
cursor.executemany("insert into t(name, id) values (?, ?)", params)

在这里,所有参数在一个bundle(连同SQL语句)中发送到数据库服务器,数据库将针对所有参数执行SQL,作为一个数据库事务。因此,这种形式的executemany()应该比默认的executemany()快得多。但是,它也有一些限制,请参见fast_executemany了解更多详细信息。你知道吗

请修改代码并重新测试:

cursor.fast_executemany = True
cursor.executemany(insert_query,df)

希望这有帮助。你知道吗

相关问题 更多 >