【问题标题】:Connect to a mysql database server through a shell script通过 shell 脚本连接到 mysql 数据库服务器
【发布时间】:2019-11-20 06:32:29
【问题描述】:

我想编写一个 shell 脚本,我想通过仅在 shell 脚本中提供用户 ID 和密码来连接到 MySQL 数据库服务器,然后运行我的 drop 并创建数据库查询。服务器将在一个不同的盒子里,比如魔方。任何帮助将不胜感激。

【问题讨论】:

  • 请发布您的一些代码/努力,然后只有我们可以帮助您。
  • 我正在使用 gcloud 进行连接。我正在编写第一次 shell 脚本,如果我听起来错了,请原谅。我登录到我的集群并运行我的 glcoud 命令 -> gcloud sql connect ql03-dd97-mysql --user=root --quiet 。所以现在,我想编写脚本直接从我的 .sh 文件中访问它,并提供 id 和密码,它应该连接它。

标签: mysql shell sh


【解决方案1】:

首先你需要一个mysql客户端,如果没有就安装它

apt-get install mysql-client

那么你必须这样写:

#!/bin/bash
USER='username'
PASS='password'
PORT=3160
HOST='hostname'
DBASE='mysqlDbName'

Query='SELECT * FROM table WHERE some=other LIMIT 10'

mysql -u$USER -p$PASS -P$PORT -h$HOST -D$DBASE <<EOF 
$Query
EOF

// or you simple write the MYSQL code like
mysql -u$USER -p$PASS -P$PORT -h$HOST -D$DBASE <<EOF
USE mysql
SHOW tables
SELECT * FROM table WHERE some=other LIMIT 10
DROP table
EOF

// or in shell script and save your result to a file
#!/bin/bash
mysql -u$USER -p$PASS -h$HOST -A \
 --default-character-set=utf8 \
 -e $Query > /home/user/result.txt

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-19
    • 2023-03-25
    • 1970-01-01
    • 2011-11-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多