Python pyodbc fetch 很慢

ced*_*d73 5 python sql sql-server odbc pyodbc

我正在使用 pyodbc 从 MSQL Server 获取一些数据。工作正常,除非检索大量数据:它真的很慢。

我有大约 4000 行,这不是一个很大的数字。

conn = pyodbc.connect('DRIVER={SQL Server};SERVER=192.168.1.10;DATABASE=MyDB;Trusted_Connection=yes;')
cur = conn.cursor()
cur.execute('SELECT * FROM myTable')
Run Code Online (Sandbox Code Playgroud)

我尝试了以下方法:

time1 = datetime.datetime.now()
a = cur.fetchall()
time2 = datetime.datetime.now()
print time2 - time1
print len(a)
Run Code Online (Sandbox Code Playgroud)

0:00:27.286000

time1 = datetime.datetime.now()
for i in range(0, 4017):
    cur.fetchone()
time2 = datetime.datetime.now()
print time2 - time1
Run Code Online (Sandbox Code Playgroud)

0:00:21.196000

time1 = datetime.datetime.now()
allIDRows = list(cur.fetchmany(4017))
time2 = datetime.datetime.now()
print time2 - time1
Run Code Online (Sandbox Code Playgroud)

0:00:23.845000

time1 = datetime.datetime.now()
a = cur.fetchmany(4017)
time2 = datetime.datetime.now()
print time2 - time1
Run Code Online (Sandbox Code Playgroud)

0:00:24.348000

def ResultIter(cursor, arraysize=100):
    'An iterator that uses fetchmany to keep memory usage down'
    while True:
        results = cursor.fetchmany(arraysize)
        if not results:
            break
        for result in results:
            yield result
time1 = datetime.datetime.now()
for result in ResultIter(cur):
    pass
time2 = datetime.datetime.now()
print time2 - time1
Run Code Online (Sandbox Code Playgroud)

0:00:31.181000

知道为什么它这么慢,我应该怎么做才能让它变快?(好吧,如果可能的话……)

谢谢

小智 0

对于仍在关注此问题的任何人,我有另一个可能有帮助的解决方案。基本上默认情况下 pyodbc 使用非常旧的 ODBC 驱动程序。如果您有类似以下内容,则可能您的 pyodbc 也设置为旧驱动程序:

driver='{SQL Server}'
Run Code Online (Sandbox Code Playgroud)

为了解决这个问题,我在连接属性中将其更改为以下内容。

driver='{ODBC Driver 17 for SQL Server}'
Run Code Online (Sandbox Code Playgroud)

起初我需要大约 30-60 秒才能运行的东西现在只需大约 5 秒即可运行。