Mysql ошибка unable to connect to localhost

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,9781 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.4k22 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:

MySQL : How to fix Can’t connect to MySQL server on localhost 10061 error

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.2k8 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

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.

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»

When you’re done installing a MySQL server application on Windows operating system, you can try to login to your MySQL server by using the mysql command from the Command Line.

But sometimes you may get the MySQL 2003 error saying it can’t connect to MySQL server as shown below:

mysql --user=[your username] --password=[your password]
ERROR 2003 (HY000): Can't connect to MySQL server on 'localhost:3306' (10061)

The error above means that your request to connect to the MySQL server has been refused.

There are two things you need to check to fix this error:

  • Make sure that your MySQL service is actually running
  • Check that you are attempting to connect to the right port number

This tutorial will help you to do both, starting with checking MySQL service status.

Make sure that your MySQL service is actually running

To fix this error, you need to make sure that your MySQL server service is actually running in the Services panel.

First, open the Windows Start menu and search for the Services panel to see the result below:

Then, scroll through the services list until you reach the services that start with "M" to look for MySQL services.

Usually, you have the MySQL version number attached to the service name.

The MySQL version installed on my computer is MySQL 8.0.26 so I have MySQL80 service listed as shown below:

If you have MySQL version 7, then you may have MySQL70 listed on the Services panel.

As you can see from the picture above, the status of MySQL80 service is empty, meaning that it’s not currently running.

If you see the same status, you can run the service by clicking the Start the service link on the left pane.

Now you can try to connect again to your MySQL server from the Command Line.

MySQL service is missing from the Services panel

If you don’t find MySQL service from the Services panel, then you may not have installed MySQL as a Windows service.

It’s always recommended to install MySQL as a Windows service so that you can start and stop a running MySQL program easily.

To install the MySQL service, you can run the mysqld --install command from the command line as follows:

mysqld --install
Service successfully installed.

Please note that you need to have Administrator access to perform the installation above.

Alternatively, you can re-run the MySQL installer program and choose to reconfigure the installed MySQL server as shown below:

In the reconfigure wizard panel, click on Next until you get into the Windows Service section.

You should check the box that says Configure MySQL Server as a Windows Service as follows:

When you’re done, click on Next and then click on Execute to run the changes.

Now you should be able to find MySQL under the Services panel.

Check that you are attempting to connect to the right port number

When you run a MySQL service on your computer, the service will start MySQL server and allows you to connect to the server under a specific port number.

By default MySQL uses port 3306 but you can check the one you are currently using in your my.ini file.

The my.ini file is a MySQL configuration file used to properly configure the running MySQL services.

When you install MySQL using the official installer, then you should have a my.ini file located under your MySQL installation folder.

For example, mine was located under C:ProgramDataMySQLMySQL Server 8.0 folder as shown below:

Once you find the file, open it and find the [client] section.

You should find the port number assigned under the section as shown below:

[client]

# pipe=

# socket=MYSQL

port=3306

[mysql]
no-beep

Once you find the port number, and the number to the mysql command when you try to login as follows:

mysql --user=[your username] --password=[your password] --port=3306

Now you should be able to connect to your local MySQL server. Nice work! 👍



Я недавно установил MySQL 5 на Windows 2003 и попытался настроить экземпляр. Все работало нормально, пока я не добрался до «применения настроек безопасности», после чего он дал мне вышеуказанную ошибку (Can't connect to MySQL server on 'localhost' (10061)).

У меня есть исключение порта 3306 в моем брандмауэре для «MySQL Server».


17831  


18  

18 ответов:

вам, вероятно, придется предоставить привилегии «localhost» в таблице пользователю. Смотрите 'GRANT' синтаксис документации. Вот пример (из какого источника).

«предоставить все привилегии на %s.* для’%s’@ ‘localhost’, идентифицированного ‘%s'»;

Это самая распространенная проблема с MySQL.

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

кроме того, убедитесь, что служба mysql запущена.

убедитесь, что у вас не включен сторонний брандмауэр или Служба безопасности Интернета.

кроме того, есть несколько страниц форума MySQL, посвященных этому:
http://forums.mysql.com/read.php?11,9293, 9609#msg-9609

попробуйте прочитать это.

получил эту ошибку на Windows, потому что мой mysqld.exe не работал.

побежал «C:Program FilesMySQLMySQL Server 5.5binmysqld» —install из командной строки, чтобы добавить его в мои службы, запустите службы.msc (start -> run), нашел службу MySQL и запустил ее.

не пришлось беспокоиться об этом оттуда.

чтобы решить эту проблему:

  1. идем в Диспетчер задач
  2. выберите вкладку Услуги
  3. найти службу MySql
  4. под управлением

вот и все.

У меня были трудности с доступом к MySQL при подключении через соединение localhost на стандартном порту 3306, который отлично работал, когда я установил и настроил его для предыдущих классов, которые я взял в MySQL и Java. Я получал ошибки, такие как» ошибка 2003 «и»не удается подключиться к серверу MySql на localhost (10061)». Я попытался подключиться как из MySQL Workbench (5.2.35 CE), так и из Netbeans (7.2). Я использую Windows 7 64 bit professional.

Я попытался ввести службы.msc в самом начале окно поиска меню, которое открыло диалоговое окно службы, чтобы показать все службы, установленные в windows. Я прокрутил вниз к MySQL и запустил эту службу. Последующие попытки подключиться к MySQL из MySQL WorkBench и из командной строки завершились успешно.

  1. убедитесь, что ваш хост-файл windows (расположен по адресу c://windows/system32/drivers/etc.host) имеет следующие линии. Если нет, добавьте его в конце

    127.0.0.1 localhost
    ::1 localhost
    
  2. иногда mysql не может вызвать Windows для принудительного запуска служб хоста, если брандмауэр блокирует его, поэтому запустите его вручную

win+выполнить>>услуги.msc, выберите «MySQL_xx», где» xx » — это имя, которое вы назначили службам хоста MySQL во время установки. Нажмите на кнопку «начать», чтобы начать с гиперссылки появился на левой стороне.

Я попробовал решение Kuzhichamadam Inn и обнаружил, что необходимо внести небольшое изменение.

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

выполнить > Services.МСЦ > правой кнопкой мыши по MySQL > «свойства» >в начало

пресс клавиша Windows + R
напишите » услуги.МСЦ» введите
ищите «MYSQL56»
напишите нажмите на нее и Запустите сервис

для локального подключения к MySql, вам не нужно настраивать брандмауэр с входящими правилами. Но даже если вы уже установка iptables разрешить TCP входящий порт 3306 и предоставить привилегию пользователю для доступа к БД локально, вы, возможно, придется настроить адрес привязки в вашем my.cnf файл, отредактируйте там адрес по умолчанию и поместите IP-адрес сервера, на котором работает MySql сервис.

run > services.msc > rightclick MySQL57 > properties >set start type option to automatic

после перезагрузки компьютера

At cmd

cd: C:

C :> cd "C:Program FilesMySQLMySQL Server 5.7bin"

станет

C:Program FilesMySQLMySQL Server 5.7bin>

тип mysql -u root -p

ie C:Program FilesMySQLMySQL Server 5.7bin> mysql -u root -p

введите пароль: ****

вот и все

это приведет к

mysql>

Я получил эту ошибку, когда у меня закончилось место на моем диске.

на выполнить тип services.msc. проверьте, работают ли Службы MySQL. Если нет, запустите его вручную. После его запуска введите MySQL Show для тестирования сервиса.

другая возможность:

существует два способа подключения клиента MySQL к серверу: через TCP/IP или с помощью сокетов. Возможно, у вас есть сервер MySQL, настроенный для поддержки сокетных соединений, но не сетевых соединений.

ничего не делать просто «сбросить по умолчанию» настройки брандмауэра он начнет работать.

Я прочитал много решений, но ничего не работало должным образом, поэтому, наконец, я сбросил настройки брандмауэра, которые работали.

наконец-то решил эту проблему.. попробуйте запустить mysql в xammp. Флажок mysql в xammp должен быть снят. тогда начинай. после этого вы можете открыть mysql, и теперь он будет подключаться к localhost

отредактируйте свой ‘ my-default.ini ‘ файл (по умолчанию он поставляется с комментариями свойств), как показано ниже ie.

basedir=D:/D_Drive/mysql-5.6.20-win32
datadir=D:/D_Drive/mysql-5.6.20-win32/data
port=8888

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

http://www.ntu.edu.sg/home/ehchua/programming/sql/MySQL_HowTo.html#zz-3.1

Так как я боролся и нашел немного другой ответ вот он:

недавно я переключил локальный сервер (интрасеть) на своем новом рабочем месте. Установлена лампа; Debian, Apache, MySql, PHP. Пользователи на работе подключают сервер с помощью имени хоста, позволяет называть его «intaserv». Я настроил все, получил его работу, но не смог подключить Мой MySql удаленно, что бы я ни делал.

Я нашел свой ответ после бесконечных попыток, хотя. вы можете иметь только один привязать-адрес и он не может быть имя хоста, в моем случае «интранет».

Это должен быть IP-адрес, например. «bind-address=192.168.0.50».

Anglais:

  • нажмите клавишу windows + R
  • пишем «Services.msc » затем нажмите Enter
  • поиск MySQL57 и щелкните правой кнопкой мыши
  • нажмите на кнопку запустить службу

Français:

  • Appuyez sur la touche Windows + R
  • Écrire «услуги.msc » Puis appuyez sur Entrée
  • Recherchez MySQL57 et clic droit
  • Cliquez sur rédémarrer
  1. щелкните правой кнопкой мыши на моем компьютере
  2. нажмите на управление
  3. перейти к службам и приложениям
  4. выберите службы и найдите MySQL service
  5. Правой Кнопкой Мыши на MySQL и выберите Start

MySQL Workbench could not connect to MySQL

MySQL Database (Db) is a database service that runs on a Local Server and on the Web. It is ideal for both small and large applications and it uses the standard SQL language. MySQL is free to download and use and has the most comprehensive set of advanced features, management tools, and technical support to achieve the highest levels of MySQL scalability, security, reliability, and uptime. The data in a MySQL database are stored in tables. A table is a collection of related data, and it consists of columns and rows, and the Db is useful for storing information categorically. This article, you will learn how to fix MySQL Workbench could not connect to MySQL server on the localhost 10061. In this article, you will learn how to fix ‘MySQL Workbench could not connect to MySQL server”

Note: It is worth noting that by default, the MySQL server listens for connections only from localhost. Which means it can be accessed only by applications running on the same host. But in production environments, you can allow remote access to the MySQL server.  

In this aspect, you will have to configure the MySQL server to listen on a specific IP address. Or all IP addresses on the server. See the following guides on MySQL. How to reset Mysql Root password, how to access MySQL Server from command Prompt, how to create and delete MySQL database, and how to migrate Veeam MsSQL Database to a new MsSQL Server.

This article shows the steps to resolve connection issues to MySQL Servers. See how to install Microsoft SQL Server 2019 and MsSQL Command line tools on Ubuntu Linux, how to uninstall Microsoft SQL Server on Windows 10 and Windows Server, and how to download and install Microsoft SQL Server 2019 Developer Edition and Microsoft SQL Server Management Studio on Windows 10 and Windows Server.

This error is shown in because the application was unable to connect to the MySQL server. There could be a number of reasons. But in my case, it was because the service was stopped and the service was not running. To fix this issue, kindly follow the steps below.

Launch MySQL Workbench to open the home screen. Existing connections are shown when you click the MySQL Connections view from the sidebar. No connections exist for first-time users.

Launch MySQL Workbench

Click on the Server Menu and click on Startup/Shutdown option as shown below

This will open up the Administration -Startup/Shutdown window. Click on Start Server

Accept the UAC. Next, you will be required to enter your password in order to start the database server. Enter your password and click on OK.

From the Administration, the Startup/Shutdown window, you should see the server is now running. And on this window, you can stop or take the server offline.

As you can see, the MySQL service is also running. And this is all that is needed to resolve this connection issue.

I hope you found this blog post helpful. You have learned how to fix the following error “MySQL Workbench could not connect to MySQL server on the localhost 10061”. If you have any questions, please let me know in the comment session.

Понравилась статья? Поделить с друзьями:
  • Mysql ошибка 267
  • Mysql ошибка 233
  • Mysql ошибка 2054
  • Mysql ошибка 2003
  • Mysql ошибка 1698