首先,创建文件(里边内容是空的):
# 创建 file1(ctl文件)
file1 = "/home/xjy/dataImport/logs/" + str(user_id) + times + ".ctl"
# 创建filename (csv文件)
filename = "/home/xjy/dataImport/data/input/" + str(user_id) + times + ".csv"
一、load_excel.ctl相当于模板
load data infile '[filename]' "str '\r\n'" INTO TABLE [table_name] APPEND FIELDS TERMINATED BY ',' trailing nullcols([column_name],task_tags_id "'[id]'")
下列代码,相当于file1按照这个load_excel.ctl这个模板来写入,只不过对table_name 、task_id等字符串,进行替代(比如我导入的是温度数据,则table_name应改成table_22)
# open()函数 ‘r’表示读, ‘w’表示写文本文件,‘wb’表示写二进制文件
# 模板load_excel.ctl, 重写入file1: sqlloader 执行入库
with open("/home/liuyy/dataImport/dataImport/load_excel.ctl", 'r')as f_in:
with open(file1, 'w')as f_out:
for line in f_in.readlines():
print ("****line***")
print line # load data infile '[filename]' "str '\r\n'" INTO TABLE [table_name] APPEND FIELDS TERMINATED BY ',' trailing nullcols([column_name],task_tags_id "'[id]'")
if line.find("[id]") >= 0 or line.find("[filename]") >= 0 or line.find(
"[table_name]") >= 0 or line.find("[column_name]") >= 0:
# 将相关属性信息进行replace,重新写入到file1
f_out.write(line.replace("[id]", id)
.replace("[filename]", file2).replace("[table_name]", tbname).replace(
"[column_name]", column_name))
那么重写的这个file1,如下:
load data infile '/home/liuyy/dataImport/data/input/admin1632490070.36.csv' "str '\r\n'" INTO TABLE table_22 APPEND FIELDS TERMINATED BY ',' trailing nullcols(T,TEMP_NE1,TEMP_NE2,TEMP_NE3,TEMP_NE4,TEMP_NE5,TEMP_NE6,TEMP_NE7,TEMP_NE8,TEMP_NE9,TEMP_NE10,TEMP_NE11,TEMP_NE12,TEMP_NE13,TEMP_NE14,TEMP_NE15,TEMP_NE16,TEMP_NE17,TEMP_NE18,TEMP_NE19,TEMP_NE20,TEMP_NE21,TEMP_NE22,TEMP_NE23,TEMP_NE24,TEMP_NE25,TEMP_NE26,TEMP_NE27,TEMP_NE28,TEMP_NE29,TEMP_NE30,TEMP_NE31,TEMP_NE32,TEMP_NE33,TEMP_NE34,TEMP_NE35,TEMP_NE36,TEMP_NE37,TEMP_NE38,TEMP_NE39,TEMP_NE40,TEMP_NE41,TEMP_NE42,TEMP_NE43,TEMP_NE44,TEMP_NE45,TEMP_NE46,TEMP_NE47,TEMP_NE48,TEMP_NE49,TEMP_NE50,TEMP_NE51,TEMP_NE52,TEMP_NE53,TEMP_NE54,TEMP_NE55,TEMP_NE56,TEMP_NE57,TEMP_NE58,TEMP_NE59,TEMP_NE60,task_tags_id "'36e171081d3b11eca5540242ac110002'")
二、loader.sh也是相当于模板
我们必须让真实的ctl来代替"[ctl]"
chmod -R 777 [ctl]
source /home/oracle/.bash_profile
sqlldr 账号/密码@IP:端口号/orcl control=[ctl] skip=1 log=[log] parallel=true
exit
同理,下边的代码是:将file1来替换【ctl】
# 模板loader.sh, 重写入file4: sqlloader 执行入库
# with open("/home/liuyy/dataImport/dataImport/loader.sh", 'r')as f_in:
# with open(file4, 'w')as f_out:
# for line in f_in.readlines():
# if line.find("[ctl]") >= 0 or line.find("[log]") >= 0:
# f_out.write(line.replace("[ctl]", file1).replace("[log]", log))
# else:
# f_out.write(line)
三、执行入库:
比如这个csv文件是:
我只想入库,除第一行所有的,在sh文件中的skip=1,即跳过第一行
sqlldr 账号/密码@IP:端口号/orcl control=[ctl] skip=1 log=[log] parallel=true