啟動Mysql服務提示Can’t connect to local MySQL server through socket的解決方案

來源:互聯網
上載者:User

標籤:

啟動Mysql服務常會提示下面錯誤:

ERROR 2002 (HY000): Can‘t connect to local MySQL server through socket ‘/var/lib/mysql/mysql.sock‘ 

這是由於修改mysql服務的了socket檔案mysql.sock位置,而導致無法通過mysql socket檔案串連到mysql服務引起的,具體解決辦法如下:


1、查看mysql服務的socket檔案位置:
mysql socket檔案的位置是在/etc/my.cnf中設定的,cat /etc/my.cnf內容如下:


[mysqld]
datadir=/storage/db/mysql
socket=/storage/db/mysql/mysql.sock
user=mysql


其中socket等於的路徑就是socket檔案的位置,我們只要修改my.cnf檔案,告訴mysql,mysqldump,mysqladmin mysql服務的socket位置在哪裡就可以。

2、修改my.cnf檔案:
在/etc/my.cnf檔案中添加如下內容,並重啟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

[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
conn.commit()
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);
}
?>

 

啟動Mysql服務提示Can’t connect to local MySQL server through socket的解決方案

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.