这篇文章给大家分享的是有关如何实现mysql/mongo导出到本地文件的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。
一. mongo导出到本地
-
#!/bin/bash
-
set -e
-
#变量声明
-
database=""
-
table=""
-
columns=""
-
query=""
-
datafile_path=""
-
#函数定义
-
usage(){
-
echo " usage(): $0 [-d 数据库名] [-t 表名 ] [-c 列名] [-q query条件 ] " 1>&2;
-
exit 1;
-
}
-
#执行
-
#检测参数 给 对应变量赋值
-
while getopts "d:t:c:q:" opt
-
do
-
case "$opt" in
-
d) database=$OPTARG ;;
-
#t) table=$(echo $OPTARG| tr '[A-Z]' '[a-z]') ;;
-
t) table=$OPTARG ;;
-
c) columns=$OPTARG ;;
-
q) query=$OPTARG ;;
-
*) usage;;
-
esac
-
done
-
shift $[ $OPTIND - 1 ]
-
echo "mongoexport --host $mongo_ip --port $mongo_port -u $mongo_user -p $mongo_password --authenticationDatabase=admin --db ${database} --collection ${table} --readPreference='secondaryPreferred' -f ${columns} --query "{${query}}" --type=csv"
-
mongoexport --host $mongo_ip --port $mongo_port -u $mongo_user -p $mongo_password --authenticationDatabase=admin --db ${database} --collection ${table} --readPreference='secondaryPreferred' -f ${columns} --query "{${query}}" --type=csv | tail -n+2 |sed 's/ObjectID[(]\([0-9a-zA-Z-]\+\)[)]/\1/i' > ${table}.csv
二. mysql 导出到本地
-
#!/bin/bash
-
set -e
-
#变量声明
-
database=""
-
table=""
-
columns=""
-
where=""
-
datafile_path=""
-
#函数定义
-
usage(){
-
echo " usage(): $0 [-d 数据库名] [-t 表名 ] [-c 列名] [-w 过滤条件 ] " 1>&2;
-
exit 1;
-
}
-
#执行
-
#检测参数 给 对应变量赋值
-
while getopts "d:t:c:w:" opt
-
do
-
case "$opt" in
-
d) database=$OPTARG ;;
-
t) table=$(echo $OPTARG| tr '[a-z]' '[A-Z]') ;;
-
c) columns=$OPTARG ;;
-
w) where=$OPTARG ;;
-
*) usage;;
-
esac
-
done
-
shift $[ $OPTIND - 1 ]
-
#echo "database=${database} , table=${table} , columns=${columns} , where=${where}"
-
#数据库链接
-
mysql_bin="mysql -h$mysql_ip -P$mysql_port -u$mysql_user -p$mysql_password --database=${database}"
-
#生成SQL语句
-
SQL_STR=""
-
if [ ${where} == "" ];then
-
SQL_STR="select "${columns}" from "${table}";"
-
else
-
SQL_STR="select "${columns}" from "${table}" where "${where}";"
-
fi
-
echo ${SQL_STR}
-
#执行SQL语句 导入到本地文件
-
$mysql_bin -N -e "${SQL_STR}" > ${table}.csv
感谢各位的阅读!关于“如何实现mysql/mongo导出到本地文件”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,让大家可以学到更多知识,如果觉得文章不错,可以把它分享出去让更多的人看到吧!