在提出这个问题时,pandas 0.23.0 刚刚发布。该版本将 .to_sql() 的默认行为从调用 DBAPI .executemany() 方法更改为构造一个表值构造函数 (TVC),该构造函数将通过使用 INSERT 语句的单个 .execute() 调用插入多行来提高上传速度。不幸的是,这种方法经常超过 T-SQL 对存储过程的 2100 个参数值的限制,从而导致问题中引用的错误。
此后不久,pandas 的后续版本在.to_sql() 中添加了一个method= 参数。默认值 - method=None - 恢复了之前使用 .executemany() 的行为,而指定 method="multi" 将告诉 .to_sql() 使用更新的 TVC 方法。
大约在同一时间,SQLAlchemy 1.3 发布,它向create_engine() 添加了一个fast_executemany=True 参数,这大大提高了使用Microsoft 的SQL Server ODBC 驱动程序的上传速度。通过这种增强,method=None 被证明至少与method="multi" 一样快,同时避免了 2100 个参数的限制。
因此,对于当前版本的 pandas、SQLAlchemy 和 pyodbc,将.to_sql() 与 Microsoft 的 SQL Server ODBC 驱动程序一起使用的最佳方法是使用fast_executemany=True 和.to_sql() 的默认行为,即,
connection_uri = (
"mssql+pyodbc://scott:tiger^5HHH@192.168.0.199/db_name"
"?driver=ODBC+Driver+17+for+SQL+Server"
)
engine = create_engine(connection_uri, fast_executemany=True)
df.to_sql("table_name", engine, index=False, if_exists="append")
对于在 Windows、macOS 和 Microsoft 支持其 ODBC 驱动程序的 Linux 变体上运行的应用程序,这是推荐的方法。如果您需要使用 FreeTDS ODBC,则可以使用method="multi" 和chunksize= 调用.to_sql(),如下所述。
(原答案)
在 pandas 0.23.0 版之前,to_sql 将为 DataTable 中的每一行生成一个单独的 INSERT:
exec sp_prepexec @p1 output,N'@P1 int,@P2 nvarchar(6)',
N'INSERT INTO df_to_sql_test (id, txt) VALUES (@P1, @P2)',
0,N'row000'
exec sp_prepexec @p1 output,N'@P1 int,@P2 nvarchar(6)',
N'INSERT INTO df_to_sql_test (id, txt) VALUES (@P1, @P2)',
1,N'row001'
exec sp_prepexec @p1 output,N'@P1 int,@P2 nvarchar(6)',
N'INSERT INTO df_to_sql_test (id, txt) VALUES (@P1, @P2)',
2,N'row002'
大概是为了提高性能,pandas 0.23.0 现在会生成一个表值构造函数来每次调用插入多行
exec sp_prepexec @p1 output,N'@P1 int,@P2 nvarchar(6),@P3 int,@P4 nvarchar(6),@P5 int,@P6 nvarchar(6)',
N'INSERT INTO df_to_sql_test (id, txt) VALUES (@P1, @P2), (@P3, @P4), (@P5, @P6)',
0,N'row000',1,N'row001',2,N'row002'
问题在于 SQL Server 存储过程(包括像sp_prepexec 这样的系统存储过程)被限制为 2100 个参数,所以如果 DataFrame 有 100 列,那么 to_sql 一次只能插入大约 20 行。
我们可以计算所需的chunksize 使用
# df is an existing DataFrame
#
# limit based on sp_prepexec parameter count
tsql_chunksize = 2097 // len(df.columns)
# cap at 1000 (limit for number of rows inserted by table-value constructor)
tsql_chunksize = 1000 if tsql_chunksize > 1000 else tsql_chunksize
#
df.to_sql('tablename', engine, index=False, if_exists='replace',
method='multi', chunksize=tsql_chunksize)
但是,最快的方法仍然可能是: