使用Execute More From pyodbc将数据帧传输到SQL Server [英] Dataframe to SQL Server using Execute many from pyodbc

查看:83
本文介绍了使用Execute More From pyodbc将数据帧传输到SQL Server的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Pyodbc将数据从DataFrame加载到SQL Server,它逐行插入,速度非常慢。

我已经尝试了两种在网上找到的方法(中等),但我没有发现任何性能改善。

尝试在SQL Azure中运行,因此SQL AlChemy不是一种简单的连接方法。请找到我遵循的方法,以及是否有其他方法可以提高批量加载的性能。

方法1

 cursor = sql_con.cursor()
cursor.fast_executemany = True
for row_count in range(0, df.shape[0]):
  chunk = df.iloc[row_count:row_count + 1,:].values.tolist()
  tuple_of_tuples = tuple(tuple(x) for x in chunk)
  for index,row in ProductInventory.iterrows():
  cursor.executemany("INSERT INTO table ([x]],[Y]) values (?,?)",tuple_of_tuples)

方法2

 cursor = sql_con.cursor() 
for row_count in range(0, ProductInventory.shape[0]):
      chunk = ProductInventory.iloc[row_count:row_count + 1,:].values.tolist()
      tuple_of_tuples = tuple(tuple(x) for x in chunk)
  for index,row in ProductInventory.iterrows():
    cursor.executemany(""INSERT INTO table ([x]],[Y]) values (?,?)",tuple_of_tuples 

谁能告诉我为什么性能没有提高1%?仍然需要同样的时间

推荐答案

尝试在SQL Azure中运行,因此SQL AlChemy不是一种简单的连接方法。

也许你只需要先跨过那个障碍。然后您可以使用 pandas to_sqlfast_executemany=True。例如

from sqlalchemy import create_engine
#
# ...
#
engine = create_engine(connection_uri, fast_executemany=True)
df.to_sql("table_name", engine, if_exists="append", index=False)

如果您有一个有效的pyodbc连接字符串,则可以将其转换为SQLAlChemy连接URI,如下所示:

connection_uri = 'mssql+pyodbc:///?odbc_connect=' + urllib.parse.quote_plus(connection_string)

这篇关于使用Execute More From pyodbc将数据帧传输到SQL Server的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆