首页 > 解决方案 > 通过 bash 脚本连接到 MySQL 不会执行查询

问题描述

我正在尝试通过 Bash 脚本连接到 localhost 上的 mysql。(在 Raspberry PI 3B+ Raspbian 上)

连接似乎有效,但不是显示查询结果,而是显示某种 mysql 帮助页面。看起来像这样:

mysql  Ver 15.1 Distrib 10.1.38-MariaDB, for ... using readline 5.2
Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.

Usage: mysql [OPTIONS] [database]

Default options are read from the following files in the given order:
/etc/my.cnf /etc/mysql/my.cnf ~/.my.cnf
The following groups are read: mysql client client-server client-mariadb
The following options may be given as the first argument:
--print-defaults          Print the program argument list and exit.
...
#!/bin/bash
username="user"
passwort="1234"
mysql -u $username -p$passwort -e "show databases;"

如何更改命令以执行给定的语句?

标签: mysqlbash

解决方案


您的密码包含一些由 shell 解释的字符,您必须通过引用来保护密码。

示例我的密码有一个(空格)

MyMac:~ e444$ u="root"
MyMac:~ e444$ p="1234 2"
MyMac:~ e444$ mysql -u$u -p$p -h 127.0.0.1 -e "show databases;"
mysql: [Warning] Using a password on the command line interface can be insecure.
ERROR 1045 (28000): Access denied for user 'root'@'172.17.0.1' (using password: YES)

在这里收到拒绝访问,因为发送的密码是1234

MyMac:~ e444$ mysql -u$u -p"$p" -h 127.0.0.1 -e "show databases;"
mysql: [Warning] Using a password on the command line interface can be insecure.
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
+--------------------+

在这里保护变量"


推荐阅读