连接MySQL数据库的两种方式介绍
连接MySQL操作是连接进程和MySQL数据库实例进行通信。从开发的角度来说,本质上是进程通信,常用的进程通信方式有管道、命名管道、命名字、TCP/IP套接字、Unix域名套接字
TCP/IP连接:
TCP/IP套接字连接方式是MySQL在任何平台都提供的一种连接方式,也是网络中使用最多的一种方式。这种方式在TCP/IP连接上建立一个基于网络的连接请求,一般情况下客户端在一台服务器上,而MySQL实例在另外一台服务器上,这两台机器通过TCP/IP网络连接
mysql> use mysql; Readingtable information for completion of table and column names Youcan turn off this feature to get a quicker startup with -A Databasechanged mysql>select user,host,password from user; +------+-------------------+-------------------------------------------+ |user | host | password | +------+-------------------+-------------------------------------------+ |root | localhost |*23AE809DDACAF96AF0FD78ED04B6A265E05AA257 | |root | server.sxkeji.com | | |root | 127.0.0.1 | | | | localhost | | | | server.sxkeji.com | | | wu | % |*00A51F3F48415C7D4E8908980D443C29C69B60C9| +------+-------------------+-------------------------------------------+ 6rows in set (0.01 sec) mysql>
首先远程连接的客户端连接的用户有权限才可以被连接,我们查看到了wu这个用户允许任何机器远程连接
# mysql -h192.168.0.110 -uwu -p Enterpassword: Welcometo the MySQL monitor. Commands end with; or \g. YourMySQL connection id is 16 Serverversion: 5.1.52 Source distribution Copyright(c) 2000, 2010, Oracle and/or its affiliates. All rights reserved. Thissoftware comes with ABSOLUTELY NO WARRANTY. This is free software, andyou are welcome to modify and redistribute it under the GPL v2 license Type'help;' or '\h' for help. Type '\c' to clear the current input statement. mysql>//显示连接成功
Unix域套接字连接:
在Linux和Unix环境下,还可以使用Unix域套接字连接。Unix域套接字其实不是网络协议,所以只能使用MySQL客户端和数据库实例在同一台服务器上的情况下使用。可以在配置文件中指定套接字文件路径,如-socket=/tmp/mysql.sock。当数据库启动之后使用如下方法查找套接字
mysql>show variables like 'socket'\G ***************************1. row *************************** Variable_name:socket Value: /var/lib/mysql/mysql.sock 1row in set (0.00 sec) mysql>
然后就可以通过套接字的方式连接了
# mysql -uwu -S /var/lib/mysql/mysql.sock Welcometo the MySQL monitor. Commands end with; or \g. YourMySQL connection id is 18 Serverversion: 5.1.52 Source distribution Copyright(c) 2000, 2010, Oracle and/or its affiliates. All rights reserved. Thissoftware comes with ABSOLUTELY NO WARRANTY. This is free software, andyou are welcome to modify and redistribute it under the GPL v2 license Type'help;' or '\h' for help. Type '\c' to clear the current input statement. mysql>