工作中有遇到需要将oracle 数据库表全部导出,还需要去除表数据中的换行符。
方案
shell 设计
封装函数
1 function con_oracle() 用于连接oracle
2 function send_file() 用于发送文件
3 主程序 使用循环将所有表导出并发送到数据服务器
主程序
程序代码
#!/bin/bash
export NLS_LANG=AMERICAN_AMERICA.AL32UTF8
current_time=$(date +"%Y-%m-%d %H:%M:%S")
echo "==============连接数据库==$current_time============================"
# 数据库连接信息
username="new_user"
password="rainbow098"
database="orclcdb"
data_dir="/home/oracle/oracle_data/"
sql_file_dir="/home/oracle/sql_script/"
remote_username="redhat"
remote_password="123456"
remote_host="rh8"
remote_dir="/home/redhat/data"
# 连接数据库
function con_oracle(){local v_sql=$1local data_dir=$2sqlplus -S $username/$password@$database << eof$v_sqlexit ;
eof
}
# 发送文件
function send_file(){
local local_file=$1scp ${local_file} ${remote_username}@$remote_host:${remote_dir}
}
# 数据导出语句
v_sql_file=${sql_file_dir}table_sql.sql;temp_file="table_sql.txt"
> ${data_dir}${temp_file}echo "==========con_oracle ===导出语句============================"
con_oracle "@${v_sql_file}" > "${data_dir}table_sql.txt"
# 删除最后一行
sed -i '$d' "${data_dir}table_sql.txt"cat ${data_dir}${temp_file} | while read linedotable_name=$(echo $line | awk -F ';' '{print $1}' | tr 'A-Z' 'a-z')table_sql=$(echo $line | awk -F ';' '{print $2}' | tr 'A-Z' 'a-z')echo "==========生成sql脚本 "$table_name"=========================="sed -e "s#v_sql#${table_sql};#g" \-e "s#v_data_dir#${data_dir}${table_name}.txt#g" \${sql_file_dir}conf_sql.sql > ${sql_file_dir}${table_name}.sqlecho "==========导出数据 "$table_name"============================="con_oracle "@${sql_file_dir}${table_name}.sql" > "${data_dir}${table_name}.txt"echo "===========发送文件 ${data_dir}${table_name}.txt=============="send_file "${data_dir}${table_name}.txt"done