python - to_sql pyodbc count 字段不正确或语法错误

标签 python sql-server pandas pyodbc

我正在从 api 网站下载 Json 数据,并使用 sqlalchemy、pyodbc 和 pandas 的 to_sql 函数将该数据插入到 MSSQL 服务器中。

我最多可以下载 10000 行,但是我必须将 block 大小限制为 10,否则会出现以下错误:

DBAPIError: (pyodbc.Error) ('07002', '[07002] [Microsoft][SQL Server Native Client 11.0]COUNT field incorrect or syntax error (0) (SQLExecDirectW)') [SQL: 'INSERT INTO [TEMP_producing_entity_details]

大约有 5 亿行需要下载,它只是以这个速度爬行。关于解决方法有什么建议吗?

谢谢

最佳答案

在提出这个问题时,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")

对于在 Microsoft 支持其 ODBC 驱动程序的 Windows、macOS 和 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 行。

我们可以使用以下方法计算所需的 block 大小

# 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)

但是,最快的方法仍然可能是:

  • 将 DataFrame 转储到 CSV 文件(或类似文件),然后

  • 让 Python 调用 SQL Server bcp 实用程序将该文件上传到表中。

关于python - to_sql pyodbc count 字段不正确或语法错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50689082/

相关文章:

python - 数组的 sklearn DeprecationWarning 真值

python-如何从文本文件中删除一行?

sql-server - 将一个表的一列与另一个表的数据匹配

sql-server - 滚动时保持报告标题可见

python - 获取数据框中特定数据点的行和列标签

python - 在 Dash 中下载 csv 文件

python - 根据 bins 组合字典键

python - 用 pandas drop row 清理嘈杂的数据

c# - SQL Server 删除数据库失败

python - 为什么在调用 '.values' 时 pd.Timestamp 转换为 np.datetime64 ?