,Mysqldump,Mysqladmin,php连接服务常会提示下面错误:
1 | ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2) |
这是由于修改mysql服务的了socket文件mysql.sock位置,而导致无法通过mysql socket文件连接到mysql服务引起的,具体解决办法如下:
1、查看mysql服务的socket文件位置:mysql socket文件的位置是在/etc/my.cnf中设置的,cat /etc/my.cnf内容如下:1 2 3 4 | [mysqld] datadir=/storage/db/mysql socket=/storage/db/mysql/mysql.sock user=mysql |
其中socket等于的路径就是socket文件的位置,我们只要修改my.cnf文件,告诉mysql,, mysql服务的socket位置在哪里就可以。
2、修改my.cnf文件:
在/etc/my.cnf文件中添加如下内容,并重启mysqls服务,即可解决mysql,mysqldump,的“Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock'”问题:1 2 3 4 5 6 7 8 9 10 11 12 | [mysqld] datadir=/storage/db/mysql socket=/storage/db/mysql/mysql.sock
[mysql] socket=/storage/db/mysql/mysql.sock
[mysqldump] socket=/storage/db/mysql/mysql.sock
[mysqladmin] socket=/storage/db/mysql/mysql.sock |
3、php连接mysql服务提示"Can't connect to local MySQL server through socket..."的解决方法
有时候mysql服务正常运行,用户名密码也完全正确,使用php的mysql_connect函数却连接不了mysql,调用php的mysql_error()函数提示“Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock'”,这是我们需要修改/etc/php.ini文件。在/etc/php.ini文件中"[MySQL]"项下找到"mysql.default_socket",并设置其值指向正确的mysql服务socket文件即可,如:1 2 3 | [MySQL] ...省略n行... mysql.default_socket = "/storage/db/mysql/mysql.sock" |
4、python连接mysql提示"Can't connect to local MySQL server through socket..."的解决方法:
在连接mysql数据库函数中指定socket文件,如下:1 2 3 4 5 6 7 8 | #!/usr/bin/python from MySQLdb import connect conn = connect(db="pzy", user="root", host="localhost", unix_socket="/storage/db/mysql/mysql.sock") cur = conn.cursor() count=cur.execute("show databases") print 'there has %s dbs' % count conn.commit() conn.close() |
5. php pdo连接mysql提示"Can't connect to local MySQL server through socket..."的解决方法:
同样在连接字符串添加mysql socket文件的位置即可,如下:1 2 3 4 5 6 7 8 | <?php $dsn = "mysql:host=localhost;dbname=pzy;unix_socket=/storage/db/mysql/mysql.sock"; $db = new PDO($dsn, 'root', ''); $rs = $db->query("SELECT * FROM qrtest"); while($row = $rs->fetch()){ print_r($row); } ?> |
报同样错误,其他可能原因:
1.查看mysql是否启动
#/usr/local/mysql/suported-files/mysql.server status
or #/etc/init.d/mysqld status
or #systemctl status mysqld.service
or #service mysqld status
如果mysql在运行,则kill或者stop
2.如果mysql能够启动,>mysql进入时报错,则:
#mysql -uroot -S /data/mysql/mysql.sock 测试socket文件是不是在那个位置,如果能够进入,则就是最上面的解决方法。
3.权限原因,很可能是没有权限在指定路径下创建 mysql.sock文件
#chown -R mysql.mysql /usr/local/mysql
#chown -R mysql.mysql /data/mysql
有些时候需要:chown -R root.root /usr/local/mysql,其他程序才能调用mysql,不报这个错误。
服务器正常启动时,会自动创建 mysql.sock文件