如何实现mysql/mongo导出到本地文件

2023-05-11,

这篇文章给大家分享的是有关如何实现mysql/mongo导出到本地文件的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。

一. mongo导出到本地

  1. #!/bin/bash

  2. set -e

  3. #变量声明

  4. database=""

  5. table=""

  6. columns=""

  7. query=""

  8. datafile_path=""

  9. #函数定义

  10. usage(){

  11. echo " usage(): $0 [-d 数据库名] [-t 表名 ] [-c 列名] [-q query条件 ] " 1>&2;

  12. exit 1;

  13. }

  14. #执行

  15. #检测参数 给 对应变量赋值

  16. while getopts "d:t:c:q:" opt

  17. do

  18. case "$opt" in

  19. d) database=$OPTARG ;;

  20. #t) table=$(echo $OPTARG| tr '[A-Z]' '[a-z]') ;;

  21. t) table=$OPTARG ;;

  22. c) columns=$OPTARG ;;

  23. q) query=$OPTARG ;;

  24. *) usage;;

  25. esac

  26. done

  27. shift $[ $OPTIND - 1 ]

  28. 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"

  29. 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 导出到本地

  1. #!/bin/bash

  2. set -e

  3. #变量声明

  4. database=""

  5. table=""

  6. columns=""

  7. where=""

  8. datafile_path=""

  9. #函数定义

  10. usage(){

  11. echo " usage(): $0 [-d 数据库名] [-t 表名 ] [-c 列名] [-w 过滤条件 ] " 1>&2;

  12. exit 1;

  13. }

  14. #执行

  15. #检测参数 给 对应变量赋值

  16. while getopts "d:t:c:w:" opt

  17. do

  18. case "$opt" in

  19. d) database=$OPTARG ;;

  20. t) table=$(echo $OPTARG| tr '[a-z]' '[A-Z]') ;;

  21. c) columns=$OPTARG ;;

  22. w) where=$OPTARG ;;

  23. *) usage;;

  24. esac

  25. done

  26. shift $[ $OPTIND - 1 ]

  27. #echo "database=${database} , table=${table} , columns=${columns} , where=${where}"

  28. #数据库链接

  29. mysql_bin="mysql -h$mysql_ip -P$mysql_port -u$mysql_user -p$mysql_password --database=${database}"

  30. #生成SQL语句

  31. SQL_STR=""

  32. if [ ${where} == "" ];then

  33. SQL_STR="select "${columns}" from "${table}";"

  34. else

  35. SQL_STR="select "${columns}" from "${table}" where "${where}";"

  36. fi

  37. echo ${SQL_STR}

  38. #执行SQL语句 导入到本地文件

  39. $mysql_bin -N -e "${SQL_STR}" > ${table}.csv

感谢各位的阅读!关于“如何实现mysql/mongo导出到本地文件”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,让大家可以学到更多知识,如果觉得文章不错,可以把它分享出去让更多的人看到吧!

《如何实现mysql/mongo导出到本地文件.doc》

下载本文的Word格式文档,以方便收藏与打印。