使用 to_sql 连接 SQL 服务器时防止超时

Preventing timing out when using to_sql to connect with SQL Server

我有一个形状为 (749588, 11) 的中型数据框,我正试图将其保存到 SQL 服务器中的 table。当我使用:

sql_members[:1].to_sql('HCC_complete'
               , con=engine
               , if_exists='append'
               , index=False
               , chunksize=10000)

它会成功地将第一行保存到 table,我可以在 SSMS 中看到它。即使我使用第一个 [:100] 也可以,但速度稍慢。

问题是当我尝试保存整个数据帧时出现以下长错误:

OperationalError: ('08S01', '[08S01] [Microsoft][ODBC Driver 17 for SQL Server]TCP Provider: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond.\r\n (10060) (SQLExecDirectW); [08S01] [Microsoft][ODBC Driver 17 for SQL Server]Communication link failure (10060)')

对我来说,这似乎是超时问题或 SQL 服务器中的某些设置。我尝试了较小的批次,但更改任何 to_sql 参数似乎都有帮助。甚至 method='multi' 也给我一个关于参数数量不同的错误。我没有用于保存到此 table 的自定义查询,如果我这样做了,为什么它适用于 < 100 行而不是所有行?

根据一些建议,我在试图将 DataFrame 保存到 SQL table 的连接 timeout=10000cursor.fast_executemany=True 中添加了一个连接超时参数。

根据我在我的引擎 url 之后添加 fast_executemany=True 的评论,这解决了问题。现在看起来像:

engine = sqlalchemy.create_engine(
            f'mssql+pyodbc://@{server_name}/{database}?trusted_connection=yes&driver=ODBC+Driver+17+for+SQL+Server', fast_executemany=True)

大约一分钟后完成。