将CSV导入Oracle表(Python)
问题描述:
我正在使用Python 3.6遍历文件夹结构,并返回所有这些CSV的文件路径,我想将其导入到两个已创建的Oracle表中。将CSV导入Oracle表(Python)
con = cx_Oracle.connect('BLAH/[email protected]: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来生产所使用的BULK INSERT SQL命令为SQL Server的功能:
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),因此性能至关重要。做这件事最有效的方法是什么?
答
批量插入使用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
你准备一个INSERT语句做。然后你存储你的文件和你的列表。最后你执行很多。它会使一切瘫痪。
你可以考虑使用[sql * loader](https://*.com/a/6198961/322909)+ python的Popen。 – John
我同意,使用Oracle Data Pump加载数据。 –