MS Access DB中的PYODBC插入语句非常慢

时间:2019-03-19 03:45:50

标签: python performance ms-access sql-insert pyodbc

我希望将我的插入语句加速到Access Db中。数据只有86500条记录,并且需要24小时以上的处理时间。我希望加快的代码部分是比较两个表的重复项。如果找不到重复项,则插入该行。我正在运行64位Windows 10、32位python 2.7、32位ms访问odbc驱动程序和32位pyodbc模块。任何帮助将不胜感激,下面的代码示例。

def importDIDsACC():
    """Compare the Ledger to ImportDids to find any missing records"""
    imdidsLst = []
    ldgrLst = readMSAccess("ActivityNumber", "Ledger")
    for x in readMSAccess("DISP_NUM", "ImportDids"):
        if x not in ldgrLst and x not in imdidsLst:
            didsLst.append(x)
    #Select the records to import
    if len(imdidsLst) > 0:
        sql = ""
        for row in imdidsLst:
            sql += "DISP_NUM = '" + row[0]
            cursor.execute("SELECT * FROM ImportDids WHERE " + sql)
            rows = cursor.fetchall()
            #Import to Ledger
            dupChk = []
            for row in rows:
                if row[4] not in dupChk:
                    cursor.execute('INSERT into Ledger ([ActivityNumber], [WorkArea], [ClientName], [SurfacePurpose], [OpsApsDist], [AppDate], [LOADate], [EffDate], [AmnDate], [CanDate], [RenDate], [ExpDate], [ReiDate], [AmlDate], [DispType], [TRM], [Section], [Quarter], [Inspected_Date], [Inspection_Reason], [Inspected_By], [InspectionStatus], [REGION], [DOC], [STATCD]) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)',
                                   str(row[1]), str(row[18]), str(row[17]), row[14], str(row[26]), row[4], row[5], row[6], row[7], row[8], row[9], row[10], row[11], row[12], str(row[1][0:3]), trmCal(str(row[21]),str(row[20]), str(row[19])), str(row[22]), str(row[23]), inspSts(str(row[1]), 0),inspSts(str(row[1]), 1), inspSts(str(row[1]), 2), inspSts(str(row[1]), 3), str(row[27]), str(row[3]), str(row[13]))
                    dupChk.append(row[4])
            cnxn.commit()

def readMSAccess(columns, table):
    """Select all records from the chosen field"""
    sql = "SELECT "+ columns +  " FROM " + table
    cursor.execute(sql)
    rows = cursor.fetchall()
    return rows

def dbConn():
    """Connects to Access dataBase"""
    connStr = """
    DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};
    DBQ=""" + getDatabasepath() + ";"
    cnxn = pyodbc.connect(connStr)
    cursor = cnxn.cursor()
    return cursor, cnxn

def getDatabasepath():
    """get the path to the access database"""
    mycwd = os.getcwd()
    os.chdir("..")
    dataBasePath = os.getcwd() + os.sep + "LandsAccessTool.accdb"
    os.chdir(mycwd)
    return dataBasePath

# Connect to the Access Database
cursor, cnxn = dbConn()

# Update the Ledger with any new records from importDids
importDIDsACC()

1 个答案:

答案 0 :(得分:1)

请勿使用外部代码检查重复项。数据库(甚至Access)的功能正在最大化其数据集操作。不要尝试重写这种代码,尤其是因为您发现它效率不高。而是将所有内容导入临时数据库表,然后使用Access(或适当的Access Data Engine)执行SQL语句以比较表,查找或排除重复的行。然后,这些查询的结果可用于创建和/或更新其他表-全部在数据库引擎的上下文中。当然,使用适当的索引和键来建立临时表可以最大程度地提高效率。

同时,在本地比较数据集(即表)以将所有值从单个数据库请求(即SQL SELECT语句)加载到某个可搜索的集合中时,通常更快(我可以说总是吗?),然后使用该内存中集合搜索匹配项。在我上一次关于最大化数据库功能的声明之后,这似乎具有讽刺意味,但是重要的想法是了解如何处理整个数据集。即使在同一台机器上,在python进程和数据库引擎之间来回传输数据也比处理python进程内的所有数据或数据库引擎进程内的所有数据都要慢得多。唯一可能没有用的时间是远程数据集太大而无法下载,但是87,000个键值绝对足够小,无法将所有值加载到python集合中。

相关问题