我在将大量数据从 Python3 快速插入 SQL Server 时遇到问题。
目标表有 9 列,3 个索引和 1 个主键。
下面的代码有效,但它比我想要的要慢得多。看下面的时间:
-- 1,000 records
In [35]: %time connection_factory.executemany(sql, args)
CPU times: user 30.2 ms, sys: 40.9 ms, total: 71.1 ms
Wall time: 3.54 s
-- 5,000 records
In [46]: %time connection_factory.executemany(sql, args)
CPU times: user 110 ms, sys: 55.8 ms, total: 166 ms
Wall time: 17 s
我已经尝试使用 sql_alchemy 并且目前正在使用 Turbodbc - 但对其他任何运行速度更快的东西都开放。
下面是我的代码示例
from turbodbc import connect, make_options
class ConnectionFactory:
def __init__(self):
self.connection = self.initialize()
@staticmethod
def initialize():
options = make_options(autocommit=True)
return connect(driver="FREETDS",
server="",
port="",
database="",
uid="",
pwd="",
turbodbc_options=options)
def execute(self, query, params=None):
try:
cursor = self.connection.cursor()
cursor.execute(query, params)
except Exception as e:
print(e)
finally:
cursor.close()
return
def executemany(self, query, params=None):
try:
cursor = self.connection.cursor()
cursor.executemany(query, params)
except Exception as e:
print(e)
finally:
cursor.close()
return
sql = """
INSERT INTO table1 (value1,
value2,
value3,
value4,
value5,
value6,
value7)
VALUES (?, ?, ?, ?, ?, ?, ?); """
args = df.to_records().tolist()
connection_factory = ConnectionFactory()
connection_factory.executemany(sql, args)
有没有人熟悉 SQL Server 和 python 的这种精确组合,可以为我指明正确的方向?