03-连接选项
-u, --user=name 指定用户名
-p, --password[=name] 指定密码
-h, --host=name 指定服务器IP或者域名
-P, --port=# 指定连接端口
这4个选项经常一起配合使用。在默认情况下,如果这些选项都不写,那么mysql将会使用'用户'@'localhost'和空密码连接本机(localhost)上的3306端口。空用户在MySQL刚刚安装完毕后会自动生成,这也就是我们只使用一个“mysql”命令就可以连接到数据库的原因。如下例中,使用“mysql”命令就可以直接连接到数据库。
[root@localhost mysql]# mysql
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 71
Server version: 5.0.41-community-log MySQL Community Edition (GPL)
Type 'help;' or '\h' for help. Type '\c' to clear the buffer.
mysql>
可以查看一下当前的连接用户:
mysql> select current_user();
+----------------+
| current_user() |
+----------------+
| @localhost |
+----------------+
1 row in set (0.04 sec)
果然,系统使用了空用户进行了连接。读者可能会想,如果删除了空用户,那么用单纯的“mysql”命令是不是就永远不能登录了呢?不是的,如果空用户被删除,mysql会接着去my.cnf里面找[client]组内的用户名和密码,如果有则按照此用户名和密码进行登录;如果没有记录此选项,则系统会使用'root'@'localhost'用户进行登录。来看下面的例子,my.cnf中有用户z1,密码为空:
[root@localhost mysql]# more /etc/my.cnf
[mysqld]
default-character-set=gbk
log-bin
datadir=/home/zzx
log
log-slow-queries
innodb_data_file_path=ibdata1:58M;ibdata2:20M:autoextend
[mysql]
default-character-set=gbk
[client]
user=z1
password=
使用mysql命令直接登录后查看当前用户:
[root@localhost mysql]# mysql
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 71
Server version: 5.0.41-community-log MySQL Community Edition (GPL)
Type 'help;' or '\h' for help. Type '\c' to clear the buffer.
mysql> select current_user();
+----------------+
| current_user() |
+----------------+
| z1@localhost |
+----------------+
1 row in set (0.00 sec)
果然,此时的默认登录用户换成了 z1@localhost。这里将[client]中选项注释后,重启服务器,再次用mysql命令直接登录:
[root@localhost mysql]# mysql
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 1
Server version: 5.0.41-community MySQL Community Edition (GPL)
Type 'help;' or '\h' for help. Type '\c' to clear the buffer.
mysql> select current_user();
+----------------+
| current_user() |
+----------------+
| root@localhost |
+----------------+
1 row in set (0.00 sec)
正如我们所料,此时的登录用户已经变成了'root'@'localhost'。
如果客户端和服务器位于同一台机器上,通常不需要指定-h选项,否则要指定MySQL服务所在的IP或者主机名。如果不指定端口,默认连接到3306端口。以下是一个远程用户用root账号成功连接到服务器192.168.7.55上3306端口的例子:
C:\mysql\bin>mysql -h 192.168.7.55 -P 3306 -uroot -p
Enter password: **
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 8 to server version: 4.1.13-standard-log
Type 'help;' or '\h' for help. Type '\c' to clear the buffer.
mysql>
注意:在正式的生产环境中,为了安全起见,一般需要创建应用账号并赋予适当权限,而不会用root 直接操纵数据库;默认端口(3306)一般不要使用,可以改为任意操作系统未占用的端口。