需求:每个小时前台生成一个追踪文件,文件名格式为yyyymmddhh,存放在linux服务器上,要求每小时将上一个小时生成的文件导入数据库
解决方案:
采用sqlldr可以快速的将外部文本文件加载到数据库中,根据要求创建控制文件和shell脚本,其中控制文件如下
[root@justin justin]# more control.ctl
load data
characterset UTF8
infile '/justin/source_file.csv'
append into table abc
fields terminated by ',' OPTIONALLY ENCLOSED BY '"'
TRAILING NULLCOLS
(
"ID" sequence(MAX,1),
"desc" char(4000),
"TIME" DATE "YYYY-MM-DD HH24:MI:SS"
)
由于要采用直接路径加载,所以必须在控制文件中就定义好字符集(需要同数据库保持一致),否则sqlldr会采用OS的字符集加载,中文出现乱码;
文本文件中没有主键ID,需要在加载的时候就要为其生成,所以采用sequence(MAX,1)函数
#!/bin/bash
ORACLE_HOME=/data/oracle/product/10205/db1
export ORACLE_HOME
folder=/justin/--文件保存路径
#get the past time value
date1=`date --date='1 hour ago' +%Y%m%d%H`
date2=`date --date='15 day ago' +%Y%m%d%H`
#rename the file generated one hour ago to source_file.csv, which would be called by control.ctl
mv "$folder""$date1" "$folder"source_file.csv--因为每次加载的文件名称都不一样,所以需要其重命名成一个固定的文件,名字需要跟control.ctl中的保持一致
#call sqlldr, with control as control.ctl
$ORACLE_HOME/bin/./sqlldr userid=justin/***** control="$folder"control.ctl readsize=500000 rows=2000 direct=true log="$folder""$date1"-51
#rename bad file if generated
if [ -f "$folder"source_file.bad ]; then
mv "$folder"source_file.bad "$folder""$date1"-51.bad
fi
#roll back the rename operation
mv "$folder"source_file.csv "$folder""$date1"
#if the file generated by 15 days ago still exist, then drop them
if [ -f "$folder""$date2" ]; then--删除过期文件
rm "$folder""$date2"
fi
if [ -f "$folder""$date2"-51.log ]; then
rm "$folder""$date2"-51.log
fi
if [ -f "$folder""$date2"-51.bad ]; then
rm "$folder""$date2"-51.bad
fi
最后将这个shell脚本加入至crontab设置每小时运行一次即可
来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/15480802/viewspace-688368/,如需转载,请注明出处,否则将追究法律责任。