在SQL Server中使用fast_executemany为TRUE时python崩溃

时间:2019-03-08 11:44:07

标签: python sql-server pyodbc executemany

我正在尝试将数据从SourceDB导入到TargetDB。相应表中只有15000行,并且用fast_executemany为False花费大约20分钟

但是当我将fast_executemany设置为true时,我的python解释器在cursorTarget.executemany(SQL1,data)上崩溃了

def ImportFunction(TargetServer,TargetDB,TargetTable,SourceServer,SourceDB,SourceTable,SQL,TCID) :
connectionStringSource = 'DRIVER={SQL Server Native Client 11.0};SERVER='+SourceServer+';DATABASE='+SourceDB+';Trusted_Connection=yes;'
connectionStringTarget = 'DRIVER={SQL Server Native Client 11.0};SERVER='+TargetServer+';DATABASE='+TargetDB+';Trusted_Connection=yes;'
connectionSource = pyodbc.connect(connectionStringSource)
connectionTarget = pyodbc.connect(connectionStringTarget)
cursorSource = connectionSource.cursor()
cursorTarget = connectionTarget.cursor()   
cursorSource.execute(SQL)
rowspart = []
while True :
    itrcount = 1
    rowspart = cursorSource.fetchmany(100)
    if not rowspart :
        break
        #break while loop
    data = rowspart
    connectionSource1 = pyodbc.connect(connectionStringSource)
    cursorSource1 = connectionSource1.cursor()
    rest = cursorSource1.execute("SELECT * FROM "+SourceTable+" WHERE 1=0")
    columnList = [tuple[0] for tuple in rest.description]
    String = ','.join(str(e) for e in columnList)
    StringSQL = "?, " * (len(columnList)-1)
    StringSQL = StringSQL+"?"
    StringSQL = " ) VALUES("+StringSQL+ ")"
    SQL1 = "insert into " + TargetTable + " ( "+ String + StringSQL
    if len(rowspart) > 50 :
        cursorTarget.fast_executemany = True 
    else :
        cursorTarget.fast_executemany = False
    try:
        cursorTarget.executemany(SQL1, data)
    except Exception as e:
        print 'error: ' + str(e)
        #break
    itrcount = itrcount + 1
    del rowspart[:]
    cursorSource1.close()
    del cursorSource1
    connectionSource1.close()

connectionTarget.commit()
cursorSource.close()
del cursorSource
connectionSource.close()
cursorTarget.close()
del cursorTarget
connectionTarget.close()

1 个答案:

答案 0 :(得分:0)

该问题仍在调查中。同时,您也许可以使用更新的ODBC驱动程序(例如用于SQL Server的DRIVER = ODBC Driver 13)继续进行操作,并且 运行pip install pyodbc == 4.0.22以使用较早版本的pyodbc。