mysql,mysqldump,Mysqladmin,php连接mysql服务常会提示下面错误:
ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2)
当使用host参数为“localhost”连接Mysql服务时,会优先使用“sock文件”进行连接,而不是使用“IP:端口”进行连接,而Mysql尝试使用“sock文件”进行连接时,却无法获取“sock文件”的位置。
要解决此错误,有两种解决方法:
- 将连接参数“host”的值由“localhost”改成“127.0.0.1”;
- 按下面方法,在“/etc/mysqlf”中指定“sock文件”位置。
1、查看mysql服务的socket文件位置:
mysql socket文件的位置是在/etc/myf中设置的,cat /etc/myf内容如下:
[mysqld]
datadir=/storage/db/mysql
socket=/storage/db/mysql/mysql.sock
user=mysql
其中socket等于的路径就是socket文件的位置,我们只要修改myf文件,告诉mysql,mysqldump,mysqladmin等mysql服务的socket位置在哪里就可以。
2、修改myf文件:
在/etc/myf文件中添加如下内容,并重启mysqls服务,即可解决mysql,mysqldump,mysqladmin的“Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock'”问题:
[mysqld]
datadir=/storage/db/mysql
socket=/storage/db/mysql/mysql.sock
[mysql]
socket=/storage/db/mysql/mysql.sock
[client]
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文件即可,如:
[MySQL]
...省略n行...
mysql.default_socket = "/storage/db/mysql/mysql.sock"
4、python连接mysql提示"Can't connect to local MySQL server through socket..."的解决方法:
在连接mysql数据库函数中指定socket文件,如下:
#!/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
connmit()
conn.close()
5. php pdo连接mysql提示"Can't connect to local MySQL server through socket..."的解决方法:
同样在连接字符串添加mysql socket文件的位置即可,如下:
<?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数据库
/etc/init.d/mysqld stop
#2.执行如下命令
mysqld_safe --user=mysql --skip-grant-tables --skip-networking &
#3.使用root登录mysql数据库
mysql -u root mysql
#4.更新root密码
mysql> UPDATE user SET Password=PASSWORD('newpassword') where USER='root';
#最新版MySQL请采用如下SQL:
mysql> UPDATE user SET authentication_string=PASSWORD('newpassword') where USER='root';
#5.刷新权限
mysql> FLUSH PRIVILEGES;
#6.退出mysql
mysql> quit
#7.重启mysql
/etc/init.d/mysqld restart
#8.使用root用户重新登录mysql
mysql -uroot -p
Enter password: <输入新设的密码newpassword>
更多推荐
连接Mysql提示Can’t connect to local MySQL server through socket的解决方法
发布评论