【问题标题】:Efficient importing CSVs into Oracle Table (Python)高效地将 CSV 导入 Oracle 表 (Python)
【发布时间】:2018-01-18 01:07:48
【问题描述】:

我正在使用 Python 3.6 遍历文件夹结构并将我想要导入到两个已创建的 Oracle 表中的所有这些 CSV 的文件路径返回。

con = cx_Oracle.connect('BLAH/BLAH@XXX:666/BLAH')

#Targets the exact filepaths of the CSVs we want to import into the Oracle database
if os.access(base_cust_path, os.W_OK):
    for path, dirs, files in os.walk(base_cust_path):
        if "Daily" not in path and "Daily" not in dirs and "Jul" not in path and "2017-07" not in path:
            for f in files:
                if "OUTPUT" in f and "MERGE" not in f and "DD" not in f:
                    print("Import to OUTPUT table: "+ path + "/" + f)
                    #Run function to import to SQL Table 1
                if "MERGE" in f and "OUTPUT" not in f and "DD" not in f:
                    print("Import to MERGE table:  "+ path + "/" + f)
                    #Run function to import to SQL Table 2

不久前,我能够使用 PHP 生成一个函数,该函数使用 SQL Server 的 BULK INSERT SQL 命令:

function bulkInserttoDB($csvPath){
    $tablename = "[DATABASE].[dbo].[TABLE]";
    $insert = "BULK
                INSERT ".$tablename."
                FROM '".$csvPath."'
                WITH (FIELDTERMINATOR = ',', ROWTERMINATOR = '\\n')";

    print_r($insert);
    print_r("<br>");

    $result = odbc_prepare($GLOBALS['connection'], $insert);
    odbc_execute($result)or die(odbc_error($connection));
}

我希望为 Python 复制这个,但一些 Google 搜索让我相信没有适用于 Oracle 的“BULK INSERT”命令。这个 BULK INSERT 命令的性能很棒。

由于我加载的这些 CSV 文件很大(2GB x 365),因此性能至关重要。最有效的方法是什么?

【问题讨论】:

  • 你可以考虑使用sql*loader + python的Popen。
  • 我同意,使用 Oracle Data Pump 加载数据。

标签: python sql oracle csv cx-oracle


【解决方案1】:

使用cx_oracle 库和命令进行批量插入

con = cx_Oracle.connect(CONNECTION_STRING)
cur= con.cursor()
cur.prepare("INSERT INTO MyTable values (
                    to_date(:1,'YYYY/MM/DD HH24:MI:SS'), 
                    :2,
                    :3,
                    to_date(:4,'YYYY/MM/DD HH24:MI:SS'), 
                    :5,
                    :6,
                    to_date(:7,'YYYY/MM/DD HH24:MI:SS'), 
                    :8,
                    to_date(:9,'YYYY/MM/DD HH24:MI:SS'))"
            ) ##prepare your statment
list.append((sline[0],sline[1],sline[2],sline[3],sline[4],sline[5],sline[6],sline[7],sline[8])) ##prepare your data
cur.executemany(None, list) ##insert

你准备一个插入语句。然后你存储你的文件和你的列表。最后你执行许多。它会使一切瘫痪。

【讨论】:

  • 这更多是我希望找到的。现在会试试这个。感谢“它会瘫痪一切”的提醒 - 在提交之前会先尝试一些 CSV。
  • 但老实说,我认为使用 sqlLoader 之类的 Oracle 工具性能会更好 ....
  • 使用 executemany(),查看 cx_Oracle 批处理错误功能以帮助诊断无效数据问题。
猜你喜欢
  • 1970-01-01
  • 2019-10-21
  • 1970-01-01
  • 1970-01-01
  • 2016-05-26
  • 1970-01-01
  • 2022-01-03
  • 2019-11-25
相关资源
最近更新 更多