Shell 读取 mysql 数据到CSV

 csv 文件以逗号分隔符

#!/bin/bash

MYSQL_HOSTNAME="xx.xx.xx.xx"
MYSQL_PORT=3306
MYSQL_USER="sss"
MYSQL_PWD="xxxxxx"
MYSQL_DB="ddd"
# 文件的保存路径,路径后要加/
RESULT_PATH1="/home/sun/"

# ================================执行内容=========================
cur_time=`date +%"Y-%m-%d %H:%M:00"`
file_time=`date +"%Y%m%d%H%M00"`
# 按ID读取
if [ ! -f "./.id" ];then
  # 文件不存在,保存一个id值到文件
  # 密码导出到环境变量,如果密码直接使用 mysql -p 会有warning
  export MYSQL_PWD=$MYSQL_PWD
  sql="SELECT MAX(id) from your_table;"
  `mysql -h${MYSQL_HOSTNAME} -P${MYSQL_PORT} -u${MYSQL_USER} ${MYSQL_DB} -Bse "${sql}" > "./.id"`
  # 下次执行会使用到 ./.id 文件
  exit 0
else
  max_id=`cat ./.id`
fi

select_sql="SELECT field1,field2,field3,field4,DATE_FORMAT(field5, '%Y-%m-%d %h:%i:%s'),field6 FROM your_table WHERE id>${max_id};"
echo "$cur_time $select_sql"
export MYSQL_PWD=$MYSQL_PWD
`mysql -h${MYSQL_HOSTNAME} -P${MYSQL_PORT} -u${MYSQL_USER} ${MYSQL_DB} -Bse "SELECT MAX(id) from your_table;" > "./.id"`
`mysql -h${MYSQL_HOSTNAME} -P${MYSQL_PORT} -u${MYSQL_USER} ${MYSQL_DB} -Bse "${select_sql}" > "$RESULT_PATH1$file_time.csv"`
# 制表符替换为逗号分隔
sed -i 's/\x09/\,/g' $RESULT_PATH1$file_time".csv"
# 判断是否是空文件
if [ ! -s $RESULT_PATH1$file_time".csv" ];then
  # 删除空文件
  `rm -f $RESULT_PATH1$file_time".csv"`
else
  exit 0
fi

你可能感兴趣的:(shell,shell,数据导出,csv)