首页 > 解决方案 > 使用 cx_Oracle executemany 将 xls 数据插入 Oracle DB

问题描述

我正在尝试使用 cx_Oracle 将 xls 文件插入到 oracle 表中。以下是我尝试实现相同目标的方式。

wb = open_workbook('test.xls')
    values=[]
    sheets=wb.sheet_names()
xl_sheet=wb.sheet_by_name(s)
    sql_str=preparesql('MATTERS') ##this is function I have created which will return the insert statement I am using to load the table
    for row in range(1, xl_sheet.nrows):
        col_names = xl_sheet.row(0)
        col_value = []
        for name, col in zip(col_names, range(xl_sheet.ncols)):
            searchObj = re.search( (r"Open Date|Matter Status Date"), name.value, re.M|re.I)
            if searchObj:                           
                if (xl_sheet.cell(row,col).value) == '':
                    value = ''
                else:
                    value = datetime(*xlrd.xldate_as_tuple(xl_sheet.cell(row,col).value, wb.datemode))
                    value = value.strftime('%d-%b-%Y ')
            else:
                value = (xl_sheet.cell(row,col).value)
            col_value.append(value)
        values.append(col_value)

    cur.executemany(sql_str,values,batcherrors=True)

但是当我针对某些文件的多个 xls 文件对其进行测试时,它会抛出 TypeError: I can't share the data due to the constraint from the client.我觉得这个问题与 excel 中列的 dtype 与 DB 相比. 有什么方法可以匹配上面值列表的 dtpes 以匹配 DB 中列的数据类型,还是有其他方法可以完成插入?我尝试使用 dataframe.to_sql 但它需要很多时间。我可以通过遍历值列表中的行来插入相同的数据。

标签: pythoncx-oracle

解决方案


我建议您将数据导入熊猫数据框,而不是在熊猫中使用数据类型变得非常容易。您可以更改整列的数据类型,然后可以轻松插入。


推荐阅读