Can not connect to mysql как исправить

MySQL — система управления базами данных (СУБД) с открытым исходным кодом от компании Oracle. Она была разработана и оптимизирована специально для работы веб-приложений. MySQL является неотъемлемой частью таких веб-сервисов, как Facebook, Twitter, Wikipedia, YouTube и многих других.

Эта статья расскажет, как определять, с чем связаны частые ошибки на сервере MySQL, и устранять их.

Не удаётся подключиться к локальному серверу

Одной из распространённых ошибок подключения клиента к серверу является «ERROR 2002 (HY000): Can’t connect to local MySQL server through socket ‘/var/run/mysqld/mysqld.sock’ (2)».

Эта ошибка означает, что на хосте не запущен сервер MySQL (mysqld) или вы указали неправильное имя файла сокета Unix или порт TCP/IP при попытке подключения.

Убедитесь, что сервер работает. Проверьте процесс с именем mysqld на хосте сервера, используя команды ps или grep, как показано ниже.

$ ps xa | grep mysqld | grep -v mysqld

Если эти команды не показывают выходных данных, то сервер БД не работает. Поэтому клиент не может подключиться к нему. Чтобы запустить сервер, выполните команду systemctl.

$ sudo systemctl start mysql        #Debian/Ubuntu
$ sudo systemctl start mysqld       #RHEL/CentOS/Fedora

Чтобы проверить состояние службы MySQL, используйте следующую команду:

$ sudo systemctl status mysql       #Debian/Ubuntu
$ sudo systemctl status mysqld      #RHEL/CentOS/Fedora

Если в результате выполнения команды произошла ошибка службы MySQL, вы можете попробовать перезапустить службу и ещё раз проверить её состояние.

$ sudo systemctl restart mysql
$ sudo systemctl status mysql

Если сервер работает (как показано) и вы по-прежнему видите эту ошибку, вам следует проверить, не заблокирован ли порт TCP/IP брандмауэром или любой другой службой блокировки портов.

Для поиска порта, который прослушивается сервером, используйте команду netstat.

$ sudo netstat -tlpn | grep "mysql"

Ещё одна похожая и часто встречающаяся ошибка подключения — «(2003) Can’t connect to MySQL server on ‘server’ (10061)». Это означает, что в сетевом соединении было отказано.

Следует проверить, работает ли в системе сервер MySQL (смотрите выше) и на тот ли порт вы подключаетесь (как найти порт, можно посмотреть выше).

Похожие частые ошибки, с которыми вы можете столкнуться при попытке подключиться к серверу MySQL:

ERROR 2003: Cannot connect to MySQL server on 'host_name' (111)
ERROR 2002: Cannot connect to local MySQL server through socket '/tmp/mysql.sock' (111)

Ошибки запрета доступа в MySQL

В MySQL учётная запись (УЗ) определяется именем пользователя и клиентским хостом, с которого пользователь может подключиться. УЗ может также иметь данные для аутентификации (например, пароль).

Причин для запрета доступа может быть много. Одна из них связана с учётными записями MySQL, которые сервер разрешает использовать клиентским программам при подключении. Это означает, что имя пользователя, указанное в соединении, может не иметь прав доступа к базе данных.

В MySQL есть возможность создавать учётные записи, позволяющие пользователям клиентских программ подключаться к серверу и получать доступ к данным. Поэтому при ошибке доступа проверьте разрешение УЗ на подключение к серверу через клиентскую программу.

Увидеть разрешённые привилегии учётной записи можно, выполнив в консоли команду SHOW GRANTS
Входим в консоль (пример для Unix, для Windows консоль можно найти в стартовом меню):

В консоли вводим команду:

> SHOW GRANTS FOR 'tecmint'@'localhost';

Дать привилегии конкретному пользователю в БД по IP-адресу можно, используя следующие команды:

> grant all privileges on *.test_db to 'tecmint'@'192.168.0.100';
> flush privileges;

Ошибки запрещённого доступа могут также возникнуть из-за проблем с подключением к MySQL (см. выше).

Потеря соединения с сервером MySQL

С этой ошибкой можно столкнуться по одной из следующих причин:

  • плохое сетевое соединение;
  • истекло время ожидания соединения;
  • размер BLOB  больше, чем max_allowed_packet.

В первом случае убедитесь, что у вас стабильное сетевое подключение (особенно, если подключаетесь удалённо).

Если проблема с тайм-аутом соединения (особенно при первоначальном соединении MySQL с сервером), увеличьте значение параметра connect_timeout.

В случае с размером BLOB нужно установить более высокое значение для max_allowed_packet в файле конфигурации /etc/my.cnf в разделах [mysqld] или [client] как показано ниже.

[mysqld]
connect_timeout=100
max_allowed_packet=500M

Если файл конфигурации недоступен, это значение можно установить с помощью следующей команды.

> SET GLOBAL connect_timeout=100;
> SET GLOBAL max_allowed_packet=524288000;

Слишком много подключений

Эта ошибка означает, что все доступные соединения используются клиентскими программами. Количество соединений (по умолчанию 151) контролируется системной переменной max_connections. Устранить проблему можно, увеличив значение переменной в файле конфигурации /etc/my.cnf.

[mysqld]
max_connections=1000

Недостаточно памяти

Если такая ошибка возникла, это может означать, что в MySQL недостаточно памяти для хранения всего результата запроса.

Сначала нужно убедиться, что запрос правильный. Если это так, то нужно выполнить одно из следующих действий:

  • если клиент MySQL используется напрямую, запустите его с ключом --quick switch, чтобы отключить кешированные результаты;
  • если вы используете драйвер MyODBC, пользовательский интерфейс (UI) имеет расширенную вкладку с опциями. Отметьте галочкой «Do not cache result» (не кешировать результат).

Также может помочь MySQL Tuner. Это полезный скрипт, который подключается к работающему серверу MySQL и даёт рекомендации по настройке для более высокой производительности.

$ sudo apt-get install mysqltuner     #Debian/Ubuntu
$ sudo yum install mysqltuner         #RHEL/CentOS/Fedora
$ mysqltuner

MySQL продолжает «падать»

Если такая проблема возникает, необходимо выяснить, заключается она в сервере или в клиенте. Обратите внимание, что многие сбои сервера вызваны повреждёнными файлами данных или индексными файлами.

Вы можете проверить состояние сервера, чтобы определить, как долго он работал.

$ sudo systemctl status mysql       #Debian/Ubuntu
$ sudo systemctl status mysqld      #RHEL/CentOS/Fedora

Чтобы узнать время безотказной работы сервера, запустите команду mysqladmin.

$ sudo mysqladmin version -p 

Кроме того, можно остановить сервер, сделать отладку MySQL и снова запустить службу. Для отображения статистики процессов MySQL во время выполнения других процессов откройте окно командной строки и введите следующее:

$ sudo mysqladmin -i 5 status

Или

$ sudo mysqladmin -i 5 -r status

Заключение

Самое важное при диагностике — понять, что именно вызвало ошибку. Следующие шаги помогут вам в этом:

  • Первый и самый важный шаг — просмотреть журналы MySQL, которые хранятся в каталоге /var/log/mysql/. Вы можете использовать утилиты командной строки вроде tail для чтения файлов журнала.
  • Если служба MySQL не запускается, проверьте её состояние с помощью systemctl. Или используйте команду journalctl (с флагом -xe) в systemd.
  • Вы также можете проверить файл системного журнала (например, /var/log/messages) на предмет обнаружения ошибок.
  • Попробуйте использовать такие инструменты, как Mytop, glances, top, ps или htop, чтобы проверить, какая программа использует весь ресурс процессора или блокирует машину. Они также помогут определить нехватку памяти, дискового пространства, файловых дескрипторов или какого-либо другого важного ресурса.
  • Если проблема в каком-либо процессе, можно попытаться его принудительно остановить, а затем запустить (при необходимости).
  • Если вы уверены, что проблемы именно на стороне сервера, можете выполнить команды: mysqladmin -u root ping или mysqladmin -u root processlist, чтобы получить от него ответ.
  • Если при подключении проблема не связана с сервером, проверьте, нормально ли работает клиент. Попробуйте получить какие-либо его выходные данные для устранения неполадок.

Перевод статьи «Useful Tips to Troubleshoot Common Errors in MySQL»

I installed MySQL using mysql-installer-5.5.20.0.msi on Windows 7.
From the cmd window, I run “mysqlshow -u root -p”. It asked for a password, then returned this error: “Can’t connect to MySQL server on ‘localhost’ (10061)” This is a bad indication of partially failed/successful installation.

After reading the page, http://dev.mysql.com/doc/refman/5.5/en/windows-troubleshooting.html, it told me to find an error log (.err) in C:Program FilesMySQLMySQL Server 5.5data. The directory exists but there is no log file.

I have a feeling this is related to the tight security of Windows 7, especially when installing a Unix based software. And yes, I am the Administrator on my PC.

Any help or suggestions is appreciated. And I can return a favor by answering Java and SQL query questions.

asked Jun 5, 2012 at 6:31

The Original Android's user avatar

12

Please Try the following steps:

  1. c:mysqlbin>mysqld –install
  2. c:mysqlbin>mysqld –initialize

then press “Windows key + R” write “services.msc“, run as admin

start MySQL service.

K. Yen's user avatar

K. Yen

1932 silver badges14 bronze badges

answered Jan 19, 2016 at 7:21

maheshDeshmukh's user avatar

5

I also faced the same issue and resolved it by below setups:

  1. Check the MYSQL service in the windows service. If it is there and not running then start it. It will solve your problem.

    You can find the services window by navigating to windows Start menu and typing ‘services’ in the search bar. Select the ‘Services’ option with the cogs next to it (not the executable file) and the below window will appear. Scroll down to find ‘MySql (version)’. When you select MySql you should see an option in the left pane that says ‘Start the service’. Click this and a dialogue should appear to indicate Windows is attempting to start the service. Once started the left pane will now give you the option to stop, pause and restart the service and you will now be able to connect to your MySql from the windows cmd line.

enter image description here

  1. If MYSQL service is not present in windows service then follow below setups.

    a. Open cmd as administrator.

    b. cd to C:Program Files (x86)MySQLMySQL Server 5.6bin

    c. Run the command:
    C:Program Files (x86)MySQLMySQL Server 5.6bin>mysqld.exe –install

    d. Check the MySql in the windows service, And if it is not running, Start it by clicking on the service.

    e. If your using XAMMP . Start MySQL at the XAMMP control Panel.


Burkely91's user avatar

answered Apr 29, 2017 at 13:23

Programming-Lover's user avatar

5

this issue is very to solve by windows server users

  1. go to this path
    C:Program FilesMySQLMySQL Server 5.1bin

  2. run this tool “MySQLInstanceConfig.exe”

and config the instatnce again and problem solved

answered Nov 18, 2013 at 9:05

shay lami's user avatar

shay lamishay lami

3943 silver badges2 bronze badges

4

The simple solution that worked for me is: change localhost to 127.0.0.1 in your database.yml or in your script if writing one.

doubleDown's user avatar

doubleDown

7,9681 gold badge32 silver badges48 bronze badges

answered Oct 27, 2012 at 3:16

Keramat's user avatar

KeramatKeramat

1211 silver badge3 bronze badges

1

Here, you need to make sure that the MySQL service is running is Windows. It might be possible that your MySQL service is not running cuurrently.

  1. Open Services window by pressing Windows+R and entering services.msc
  2. Find out MySQL right click and select start.

It works.

7bStan's user avatar

7bStan

1601 gold badge4 silver badges13 bronze badges

answered Apr 11, 2020 at 8:16

Arianne Hernandez's user avatar

1

I had this error – stupid mistake was, I was using -p3307 to specify port, whereas I should have used -P3307, i.e. capital P. Small ‘p’ is for password arg 🙂

answered Aug 26, 2014 at 13:15

Frederik Struck-Schøning's user avatar

In Windows 7

  1. press Windows+R it opens Run
  2. Enter services.msc
  3. Find out mysql right click and start
  4. if mysql was not found
    1. Run cmd as administrator
    2. goto C:Program Files (x86)MySQLMySQL Server 5.6bin directory(to go back use cd..) and type mysqld.exe --install
  5. follow step 3

That’s all

barbsan's user avatar

barbsan

3,40811 gold badges21 silver badges28 bronze badges

answered Jun 10, 2017 at 18:13

nikhil's user avatar

nikhilnikhil

811 silver badge1 bronze badge

2

I solved this by adding the following arguments to the command line string:

mysql --user username --password password --host localhost --port 3306 databasename < "system path to .sql file"

Without the --host and --port arguments, especially if you change the port to let’s say 3307, which is a non default value, will cause this error.

barbsan's user avatar

barbsan

3,40811 gold badges21 silver badges28 bronze badges

answered Jan 14, 2018 at 9:59

Charles Robertson's user avatar

2

I got this error in command prompt when I tried to open MySQL from cmd “mysql -u root -p”
Can’t connect to MySQL server on ‘localhost:3306’ (10061)
It was because I changed my port during the installation of MySQL community server as I had XAMPP server installed and running as well which was not allowing me to use the port 3306.
So basically I had 2 MySQL servers installed in my system.

  1. MySQL community server.
  2. XAMPP server.

If anyone had this same issue this is how I fixed it.
Step 1: Reconfigure MySQL server to port 3306
Step 2: Reconfigure XAMPP to use a different port other than 3306

Note: Stop the XAMPP server before following the steps.

Step 1: Reconfigure MySQL server to port 3306

  1. Click Start and open MySql installer – community
  2. Click on reconfigure button in front of MySql server
  3. Type 3306 in port. Execute and complete the installation.
    enter image description here

Step 2: Reconfigure XAMPP to use a different port other than 3306

  1. Open XAMPP and change the port other than 3306 in two files
    my.ini under MySQL
    and php.ini under Apache
    enter image description here

Now everything seems to be working fine for me. I was able to get into MySQL community server from cmd and I can use XAMPP server as well.

Dharman's user avatar

Dharman

30.3k22 gold badges84 silver badges132 bronze badges

answered Aug 11, 2021 at 15:16

mrsagar105's user avatar

mrsagar105mrsagar105

1762 silver badges6 bronze badges

I have Windows 8.1 and I too had this problem. My teacher told me it was probably because my MySQL server had stopped running. She told me to go into the Computer Management utility (right click the lower-most left hand corner of the screen on Windows 8.1 to access Computer Management). Then under Services and Applications, open up the Services and find MySQL. You should be able to right-click on MySQL and restart it.

answered Jan 26, 2015 at 7:04

Avilio's user avatar

AvilioAvilio

5716 silver badges4 bronze badges

  1. In Start Menu, search for “mysql”. Among the results, you should see the “MySQL Installer – Community”. Run it.

  2. MySQL Installer window will show up as shown below. Find “MySQL Server” under Product and click on “Reconfigure” link.

  3. The MySQL Installer will show up (same one you used for the first MySQL Server installation). Go through all the steps.

  4. After the MySQL Installer was finished, I started the MySQL service again. This time, the “Startup Message Log” on The MySQL Notifier was showing that the server started successfully:

answered Aug 30, 2018 at 15:30

nishith kumar's user avatar

This is the easiest solution and worked for me.

  • Go to where you downloaded
    “mysql-installer-web-community-8.0.19.0.msi”, file for installing
    mysql.
  • Run this by double clicking on it. (No need to uninstall anything)
  • Click on “reconfigure” beside the MySql server.
  • Agree everything which comes in middle, provide password for root where asked.
  • Finish. That’s it you’re good to go.

answered May 19, 2020 at 6:11

Rama Krishna Reddy's user avatar

2

For the 5.7 version, I had the same problem and a simple fix did the trick. As Installed the workbench 5.7 there was another “software” of sorts called the “MySQL Installer Community”. I ran this and ran the “Reconfigure” for the MySQL server. It took about a minute and the problem was no longer there.

Hope it works!.(Keep in mind i was using the 5.7 version)

answered Feb 27, 2017 at 22:08

user0221441's user avatar

user0221441user0221441

3684 silver badges11 bronze badges

Just turn off the firewall and remove the instance configuration. Add a new instance for the server.![Disable Firewall][1]
Give he port number correctly as 3306 as default

answered Jul 25, 2013 at 17:41

Prabhakar's user avatar

Solution 1:

For 32bit:
Run “mysql.exe” from: C:Program FilesMySQLMySQL Server 5.6bin

For 64bit:
Run “MySQLInstanceConfig.exe” from: C:Program FilesMySQLMySQL Server 5.6bin

Solution 2:

The error (2002) Can’t connect to … normally means that there is no
MySQL server running on the system or that you are using an incorrect
Unix socket file name or TCP/IP port number when trying to connect to
the server. You should also check that the TCP/IP port you are using
has not been blocked by a firewall or port blocking service.

The error (2003) Can’t connect to MySQL server on ‘server’ (10061)
indicates that the network connection has been refused. You should
check that there is a MySQL server running, that it has network
connections enabled, and that the network port you specified is the
one configured on the server.

Source: http://dev.mysql.com/doc/refman/5.6/en/starting-server.html
Visit it for more information.

answered Nov 12, 2014 at 17:35

Muhammad Rehan Qadri's user avatar

1

I had the same error. I resolved in this way

Go to start- MySQL Installer-community and run again the installer as a re-configuration(you will be asked so).

Once asked if you want make MySQL instance to run as a Windows service, check the box.

In case would do not work, try unistalling and installing again, and check the box to run MySQL as Windows service.

answered Jun 8, 2016 at 16:28

Carmine Tambascia's user avatar

3

From what I’ve gathered this means the mysql service (mysqld) isn’t running.

  • First make sure it is installed as a windows service : Run

"C:Program FilesMySQLMySQL Server 5.5binmysqld" --install

from the command line.

  • Next, start it up :

services.msc > MySQL > start

If it fails to restart, then you can follow these steps :

  • open the command line as an administrator :
    cmd.exe > open as administrator
  • run "C:Program FilesMySQLMySQL Server 5.7binmysqld" --verbose

it should fail and put the error log in a directory named data under C:Program FilesMySQLMysSQL Server 5.7 . If it fails to create data for some reason, do it manually under that directory and try again. If you can figure out what’s missing from what’s in that log, then good, you’re done.

If you’ve still got no luck, this is how I did it :

  • goto C:ProgramDataMySQL and copy the file named my.ini to C:Windows

  • try to start the service again from the command line :
    "C:Program FilesMySQLMySQL Server 5.7binmysqld" --verbose

If it doesn’t display any error, than the service startup was successfull. If it’s still not working, than delete that my.ini you just copied from C:Windows and start the service from the command line once again.

it should work now

answered Oct 31, 2016 at 18:37

Paul Mira's user avatar

Paul MiraPaul Mira

711 silver badge3 bronze badges

if it is showing error 2003 (HY000): Can’t connect to MySQL server on localhost (10061) than

  1. Search services.msc in run
  2. goto mysql properties
  3. copy the mysql service name
  4. start cmd as administrator
  5. write: net start mysqlservicename .i.e mysql57 or etc it will show mysql is starting.

Christopher Moore's user avatar

answered Apr 7, 2017 at 8:31

neo.abi1000's user avatar

For me, three steps solved this problem on windows 10:

I downloaded MySQL server community edition zip and extracted it in the D drive. After that I went to bin folder and did cmd on that folder. I followed the below steps and all works:

D:toolsmysql-8.0.17-winx64bin>mysqld -install
Service successfully installed.

D:toolsmysql-8.0.17-winx64bin>mysqld --initialize
D:toolsmysql-8.0.17-winx64bin>net start mysql
The MySQL service is starting...
The MySQL service was started successfully.

Kevin's user avatar

Kevin

16.1k8 gold badges56 silver badges74 bronze badges

answered Aug 20, 2019 at 11:46

vikash chauhan's user avatar

I too had this problem, its easy to solve:

Go to Control panel – System and maintenance – System – Advanced system settings – Environment variables – System variables – path – click edit – add

"c:xamppmysqlbin" – it should look like this :

Program Files (x86)NVIDIA CorporationPhysXCommon;C:Program Files (x86)InteliCLS Client;C:Program FilesInteliCLS Client;%SystemRoot%system32;%SystemRoot%;%SystemRoot%System32Wbem;%SYSTEMROOT%System32WindowsPowerShellv1.0;C:Program FilesIntelIntel(R) Management Engine ComponentsDAL;C:Program FilesIntelIntel(R) Management Engine ComponentsIPT;C:Program Files (x86)IntelIntel(R) Management Engine ComponentsDAL;C:Program Files (x86)IntelIntel(R) Management Engine ComponentsIPT;C:Program Files (x86)IntelOpenCL SDK2.0binx86;C:Program Files (x86)IntelOpenCL SDK2.0binx64;C:Program Files (x86)Windows LiveShared;C:Program Files (x86)QuickTime AlternativeQTSystem;c:xamppmysqlbin

And don’t forget to start MySQL from control panel of Xampp.

Valentin Despa's user avatar

answered Jun 3, 2013 at 8:31

Siddharth Patel's user avatar

Siddharth PatelSiddharth Patel

1931 gold badge2 silver badges15 bronze badges

1

I found the same error re occurring even after I tried all the above solutions given above. I had even tried version 5.7 and few more. Guys don’t waste your time trying to fix it. Rather install version 5.5. It’s working perfectly fine without any unnecessary error.

answered Jul 1, 2018 at 16:48

Shruti's user avatar

Well in my case I just opened services.msc using run and restarted 2 of the services related to mysql and it worked!

answered Sep 21, 2018 at 7:28

Aditya's user avatar

In case of Xampp Installation.

Go to your xampp installation and mysql folder, for my case: C:xamppmysql

Run the file “resetroot.bat” from cmd or explorer.

My installation started working!!!

answered Nov 23, 2018 at 8:52

Sachin's user avatar

The solution that fixed the issue was using the following steps:

In Start Menu, search for “mysql”. Among the results, you should see the “MySQL Installer – Community”. Run it.
MySQL Installer window will show up as shown below. Find “MySQL Server” under Product and click on “Reconfigure” link.
MySQL Installer Community

The MySQL Installer will show up (same one you used for the first MySQL Server installation). Go through all the steps.

After the MySQL Installer was finished, I started the MySQL service again.

answered Dec 16, 2018 at 16:49

ankit715's user avatar

Don’t do useless stuff like reconfigure, stop MySQL and start MySQL in service.
Just reinstall the MYSQL server and again install it in your system.
Remember only uninstall MySQL server and nothing else.
All the problem will be solve automatically

answered Aug 6, 2019 at 16:32

VINEET KUMAR's user avatar

The main reason for this kind of error is you might have uninstalled Mysql server application. Install it and then give it a go.

answered Aug 26, 2019 at 9:28

Prateek Gowda's user avatar

I had the same issue and basically resolved it by pointing to a specific port number that my MySQL server was running on. Below is the command. Please edit the code to fit your case i.e your port number,your mysql server username,your password.

    mysql -u root -pYourMysqlRootPassword -P3307 

answered Oct 11, 2019 at 11:35

Tom Munyiri's user avatar

Tom MunyiriTom Munyiri

1562 silver badges5 bronze badges

  1. Create the temp folder c:/mysqltmp
  2. In my.ini file under [mysqld] add the line
    tmpdir=c:/mysqltmp
  3. Add full privileges to user NETWORK SERVICE for “C:ProgramDataMySQLMySQL Server X.YDataibdata1″ file
  4. Start service

These are steps for the same problem with MySQL5.7 and MySQL8.0 on Windows 10

answered Oct 11, 2019 at 21:03

nesomis's user avatar

На сайте ошибка базы данных

На сайте может отображаться одна из следующих ошибок подключения к базе данных:

  • «Error Establishing a Database Connection»,
  • «Database connection error (2): Could not connect to MySQL»,
  • «DB error»,
  • «Could not connect to MySQL»,
  • «Невозможно подключиться к базе данных».

Ошибку могут вызвать две причины: сервер баз данных недоступен или неверно прописаны реквизиты подключения к базе данных. В первую очередь убедитесь, что сервер баз данных доступен. Если ошибка всё равно появляется, решите проблему по инструкции ниже.

Что делать, если неверно прописаны реквизиты подключения к базе данных

Ошибка может возникать, если в конфигурационном файле сайта неправильно указаны реквизиты базы данных: сервер, имя базы данных, имя пользователя и пароль.
Чтобы проверить реквизиты:

  1. 1.

    Определите, как называется конфигурационный файл сайта. Если ваш сайт сделан на CMS, воспользуйтесь инструкцией: Где CMS хранит настройки подключения к базе данных. Если у вас самописный сайт, обратитесь к его разработчику или в службу поддержки.

  2. 2.

    Войдите в панель управления хостингом, найдите и откройте конфигурационный файл. Он может располагаться как в корневой папке, так и в других директориях сайта.

  3. 3.

    Проверьте в файле реквизиты. В качестве сервера базы данных должен быть прописан localhost (обратите внимание, не 127.0.0.1). Если вы используете удалённую базу данных на каком-либо другом сервере, пропишите его IP-адрес и убедитесь, что сервер доступен.

  4. 4.

    Проверьте в файле имя базы данных (логин) и имя пользователя базы данных. Если вы используете базу данных по умолчанию, то они должны совпадать с именами, указанными в Личном кабинете: Доступы к MySQL. Если вы создавали новую базу самостоятельно, реквизиты можно посмотреть в панели управления.

  5. 5.

    Обновите пароль базы данных. Скопируйте пароль, который указан в конфигурационном файле. Задайте его в качестве нового пароля пользователя базы данных: Как изменить пароль пользователя базы данных.

Готово, теперь ошибка должна быть устранена.

In mysql, Can’t connect to MySQL server on localhost error occurs when mysql is unable to connect to localhost due to the connection issue with mysql or a database configuration issue with mysql. You may see an error Can’t connect to MySQL server on ‘127.0.0.1’ when you connect to ip and unable to connect to localhost 3306. You can’t connect to mysql server on localhost or ip 127.0.0.1 (3306) because either the mysql server may not be started or it may not be running, or the network connection to the mysql server is not established, or the mysql server port is different.

Some times, the application can’t connect to local mysql server or mysql could not connect server may not be running or mysql unable to connect to localhost:3306. The application can’t connect to mysql server on ‘localhost:3306’.

If you are trying to access mysql server from a remote server, the error message “Can’t connect to MySQL server on ‘ localhost ‘” may be displayed in the application. This error occurs if the application is unable to connect to mysql server due to a variety of reasons. In this post, we will see the error message “Can’t connect to MySQL server on ‘ localhost ‘” and how to fix this error.

The error message indicates that there is a problem when connecting to mysql from the calling application. If you identify a connectivity issue, the error message will be fixed.

Can't connect to MySQL server on 'localhost'
Can't connect to local MySQL server through socket '/tmp/mysql.sock'

Root Cause

The error is shown in the application because the application was unable to connect to the mysql server. There could be a number of reasons. This issue is caused by a network failure.

The network failure could be on mysql server side or on the connecting application side. The other reason is that the mysql server is not running on the server. Mysql may be shut down manually, or mysql may not be running on the server machine due to some error.

Solution 1

If the database is running on the local machine, run the ping command with localhost. If the database is running on the remote server, ping the ip of the database server. In this way, we can validate the database server is alive or shutdown or network issue. If the ping does not respond, check that the server is switched on. Check that the network cable is connected correctly.

For local machine

$> ping 127.0.0.1

For remote server

$> ping <ip of the remote server>

$> ping 172.168.1.3

Solution 2

Check that mysql is running or not in the database server. The mysql server may be switched off or stopped due to some critical error. try to restart the mysql server. Check the following command to check whether the mysql server is running or not.

$> netstat -ln | grep mysql

fcc1dd9a70716e73 stream      0      0 fcc1dd9a734eb92b                0                0                0 /tmp/mysqlx.sock
fcc1dd9a707174b3 stream      0      0 fcc1dd9a732f1f7b                0                0                0 /tmp/mysql.sock

The command above shows the network status of the mysql command. The command below will show whether or not the mysql port is listening. The default port number is 3306.

$> netstat -ln | grep 3306

tcp4       0      0  127.0.0.1.3306         127.0.0.1.53815        ESTABLISHED
tcp4       0      0  127.0.0.1.53815        127.0.0.1.3306         ESTABLISHED
tcp4       0      0  127.0.0.1.3306         127.0.0.1.53814        ESTABLISHED
tcp4       0      0  127.0.0.1.53814        127.0.0.1.3306         ESTABLISHED

If the above two commands do not return the expected result, check whether the mysql process is running or not using the following command.

$> ps -ax | grep mysql
  113 ??         4:47.15 /usr/local/mysql/bin/mysqld --user=_mysql --basedir=/usr/local/mysql  ... ... ... ... ... ... ... ... --early-plugin-load=keyring_file=keyring_file.so

Solution 3

If mysql is running, check the status of mysql service. If the server appears to be running. Stop the server and restart the service again. If mysql server is hung due to issues such as memory issues, the network issue will be resolved. Use the command below to check the service

$> sudo server mysql status

$> sudo server mysql stop

$> sudo server mysql start
$> sudo /etc/init.d/mysqld status

$> sudo /etc/init.d/mysqld stop

$> sudo /etc/init.d/mysqld start

Solution 4

The mysql server is running without error. Network issues have been resolved and no network issues have been identified. Now connect to mysql server using mysql command. You can also check using the telnet command

$> telnet 172.168.1.3 3306
$> mysql -u root -p -h <host name/ip>

if the port is different from the default port 3306

$> mysql -u root -p -h <host name/ip> -P <port>

Solution 5

If the above command is working successfully and you still see error in mysql. Check out my.cnf file. My.cnf file contains all configurations of mysql. Run the command below to find the location of my.cnf file,

$> mysql --help | grep my.cnf

or just run 

$> mysql --help

Open my.cnf file and search for the word bind-address. If there is an existing change as below. If it doesn’t exist, add the line below.

to refer the localhost 
bind-address = 127.0.0.1

to refer for any address
bind-address = 0.0.0.0

Solution 6

If all of the above steps are checked and configured, restart the mysql server. All changes will be updated and start with a new configuration. If there is an error in the configuration, mysql will throw an error and will not start the server. Run the command below to check and restart mysql server

$> sudo server mysql status

$> sudo server mysql stop

$> sudo server mysql start

Solution 7

Start the mysql server with install and initialize option and check the mysql server is running or not. if you are using windows, run the mysql server as admin.

C:Program FilesMySQLMySQL Serverbin>mysqld --install

C:Program FilesMySQLMySQL Serverbin>mysqld --initialize

Solution 8

If you are using windows operating system and mysql database is installed newly, then use “MySQL Installer – Community” from the menu to reconfigure. select “mysql server” in the product tab and click the “reconfigure” in the “Quick Action” tab. This will reconfigure the mysql database.

In this post, learn how to fix Can’t connect to MySQL Server. You may get this error while installing MySQL on Windows 10 and opening “MySQL Workbench” for the first time. Below is the exact error.

Error

Following is the error:

Cant connect to MySQL Server. MySQL Workbench could not detect any MySQL running

Fix Can’t connect to MySQL Server Error

Step1: To fix the issue, go to START and type “Services” as shown below:

Fix Can't connect to MySQL Server go to MySQL Services

Step 2: Now, look for MySQL80 under Services as shown below:

MySQL80 under Services

Right click and Stop MySQL80:

Stop MySQL 80

Step3: After stopping the server, right click again and select Properties:

Reach MySQL80 Properties

Step4: Now, we will reach MySQL80 Properties:

Reached MySQL80 Properties

On clicking Log On, the following Network Service account will be visible:

Logon section visible

Click “Local System Account”, then apply and at last, OK:

Click Local System Account to fix Can't connect to MySQL Server

Step5: Right click and START the server as shown below. This will connect to MySQL Server:

connect to MySQL Server

Now, go to start, type “MySQL Workbench” and open it. The same will work.

Follow the below videos for MySQL Server and Workbench:

  • Create a new database and table in MySQL Workbench
  • Create a new database in MySQL

Video Tutorial

If you’d like to see video tutorial and fix the issue, then refer the below video,

If you liked the fix, spread the word and share the link and our website Studyopedia with others.

Support us: DONATE

Read More


  • Fix MySQL Bad Handshake: Failed to Connect to MySQL at 127.0.0.1;3306 with user root
  • How to Fix MySQL ERROR 1045 (28000) Access denied for user [email protected]
  • Fix MySQL No Packages Found – Did not find packages in the current bundle suitable…
  • Resolving Drupal Installation PHP OPcode Caching Not Enabled Warning

Studyopedia Editorial Staff


Studyopedia Editorial Staff

[email protected]

We work to create programming tutorials for all.

Добавить комментарий