一、登录mysql
登录本地的mysql
mysql -h localhost -u root -p
参数解释:
-h host 主机名称的意思 由于我们登录的不是远程服务器,而是自己本地的mysql服务器,故用localhost 。如果不写,也可以,默认登录localhost
-u username 用户名 即登录数据库的用户名称。
-p password 密码 即登录数据库的密码 ,如果 在后面写密码,则-p后面不能有空格
如果密码有特殊字符,所以用双引号包裹起来,如问号???
这是官方文档解释;
for password options, the password value is optional:
If you use a -p
or --password option and specify the password value, there must be no space between -p
or --password= and the password following it.
If you use a -p
or --password option but do not specify the password value, the client program prompts you to enter the password. The password is not displayed as you enter it. This is more secure than giving the password on the command line. Other users on your system may be able to see a password specified on the command line by executing a command such as ps auxw.
具体就是:对于password选项,此选项是可选的
如果你明确指定了-p或者--password的值,那么-p或者--password和密码值之间是不能有空格的。
如果你使用了-p或者--password选项但是没有给出password值,客户端程序提示您输入密码。
For mysql, the first nonoption argument is taken as the name of the default database. If there is no such option, mysql does not select a default database.
对于MySQL,第一个非选项参数被当作默认数据库的名称。如果没有这样的选项,MySQL就不会选择默认数据库。
也就是说在命令行中,你的mysql密码和-p或者--password参数之间有空格,mysql会认为你输入的是登录mysql后自动选择的数据库,而不是你所期望的密码
当然命令行连接数据库还有其它参数,这里主要介绍几个经常使用的,其它请参考https://dev.mysql.com/doc/refman/5.5/en/connecting.html
二、登录mysql的同时并且执行SQL语句
mysql -h localhost -u root -p123 -P3306 aaa -e "select * from runoob_tbl;"
前面几个就不赘述了,
主要注意 -e 后面的sql语句的写法, 必须用双引号给整条sql语句给括起来。
其中 aaa是我的数据库中的一个数据库名称。
runoob_tbl是我的数据库aaa下面的一个表的名称。
执行效果如下图
先不输入密码也行,这样别人就看不到你的密码了,只输入-p 然后空格