shell脚本中登录mysql,执行sql

ETL日常开发过程中涉及的数据库有oracle、mysql、db2 ,暂时没有涉及到用shell脚本对mysql库中的表,进行操作,先尝试一下以备不时之需
mysql -h 127.0.0.1 -P 3306 -u root -pYourPassword -D YourDbName

方式一:mysql -u root -pmysql < 注:密码与-p之间不能有空格,否则不能识别密码,EOF中间的sql语句,与mysql正常语句无异

  1 #!/bin/bash
  2 echo "链接mysql"
  3 mysql -u root -pmysql <<EOF
  4 use shelltest;
  5 select * from student;
  6 EOF
  7 echo "连接成功"

执行结果:

python@ubuntu:~/shellscrip$ ./mys_connec.sh 
链接mysql
mysql: [Warning] Using a password on the command line interface can be insecure.
id	name
1	tom
连接成功

方式二:mysql -u root -pmysql -e “${sql}”

  1 #!/bin/bash
  2 echo "链接mysql"
  3 sql="use shelltest;
  4 select * from student;"
  5 mysql -u root -pmysql -e "${sql}"
  6 echo "连接成功"

执行结果:

python@ubuntu:~/shellscrip$ ./mys_connec.sh 
链接mysql
mysql: [Warning] Using a password on the command line interface can be insecure.
+------+------+
| id   | name |
+------+------+
|    1 | tom  |
+------+------+
连接成功

你可能感兴趣的:(shell入门,shell)