Mysql workbench ошибка подключения к серверу

I also struggled with this problem for quite a while.

I came accross this interesting thread from MySQL forum: http://forums.mysql.com/read.php?11,11388,11388#msg-11388

I also came accross (obviously) some good SO Q/A.

It seems that the message mentioned in «user948950» ‘s question can be coming from a wide range of reasons: log file too big, incorrect mysql.ini file values, spaces in the file path, security/acl issue, old entries in the registry, and so on.

So, after trying for 3h to fix this… I abandonned and decided to do a good old re-install.

This is where this post from (again) this MySQL thread came in useful, I quote:

Gary Williams wrote: Hi Guys,

I’ve had exactly the same problem and this is how I got it working
for me, starting with a non working installation.

  1. Stop the windows service for any existing mysql installation.

  2. Uninstall Mysql.

As with most uninstalls, old files are left behind. If your directory
is C:mysql etc then delete the innob, etc, files but leave the
directories themselves as well as any existing databases in ‘data’.
If your directory is C:Program Files etc, delete all the mysql
directories.

  1. It’s now worth running regedit to make sure the old registry entries are deleted as well by the uninstall. If not, delete them.

  2. It’s ok to use the new .msi installer (essential files only), however ….

  3. Do not use their default install path! Some genius set a path with spaces in it! Choose the custom install and select a sensible path,
    ie, C:mysql (note from Adrien: C:mysqldata for … the data)

  4. Do not choose to alter the security settings. Uncheck the relevant box and the install will complete without having to set a root
    password.

I think I have remembered everything.

Good luck

Gary

I did get into troubles when simply copy/pasting the databases I had in my previous «data» directory to the new one. So the work around I found was to export each database (I know… a lot of fun) and then re-import them one by one.

FYI: I used the following command to import C:/<MySQLInstallDir>/My SQL Server x.x/bin/mysql -u root -p <dbName> < "<dirPathOfDump><dumpName>.sql", that is for instance C:/mysql/MySQL Server 5.6/bin/mysql -u root -p mySupaCoolDb < "C:mySupaCoolDbDump20130901.sql"

I’m trying to connect to mysql workbench but I get the following error

Error Message
Cannot Connect to Database Server

Your connection attempt failed for user ‘root’ from your host to server at
127.0.0.1:3306:
Could not open database.

Please:
1. Check that mysql is running on server 127.0.0.1

  1. Check that mysql is running on port 3306 (note: 3306 is the default, but this can be changed)

  2. Check the root has rights to connect to 127.0.0.1 from your address (mysql rights define what clients can connect to the server and from which machines)

  3. Make sure you are both providing a password if needed and using the correct
    password for 127.0.0.1 connecting from the host address you’re connecting

When I Test Connection, the parameters are correct, and actually I can enter and manage database in console.
When I installed Mysql for first time I could enter to Workbench one time and if I closed Workbench I had to restart my PC to connect another time.
I reinstalled 2 or 3 times Mysql server and Workbench and now I cannot connect from Workbench even once.

asked Mar 9, 2015 at 19:38

Fernando Gonzalez's user avatar

8

I faced similar issue and resolved it by following these steps:

  1. In the terminal, execute this command
    mysql -u root -p -h localhost -P 3306
  2. Enter the password
  3. This will be displayed
    Welcome to the MySQL monitor. Commands end with ; or g.
    Your MySQL connection id is 18
    Server version: 8.0.16 Homebrew
  4. Now do,
    ALTER USER ‘root’@’localhost’ IDENTIFIED WITH mysql_native_password BY ‘root’;
  5. Now you should be able to login and connect to DB in the workbench with password ‘root’

answered Jun 24, 2020 at 19:19

CodeGirl's user avatar

I don’t know if it helps anyone, but I had the same problem on windows after updating from MySQL 5.7 to 8.0.

The solution for me was to go to services.msc, stop the MySQL service and start the «MySQL80» service instead.

Then I restarted MySQL Workbench (run as admin) and it worked.

answered Jan 3, 2021 at 12:59

Elias M.'s user avatar

Please make sure that You have Downloaded MySQl server while dowloading MySQl workbench from MySQl installer (if you have checked Custom download)

answered Mar 26, 2020 at 11:57

Sachwini khatri's user avatar

I had the same issue a few days ago. As I could see in the original question, there has been multiple MySQL installation on the same computer — the same flow I tried after failing in the first attempt.

In the case we are trying to reinstall MySQL, we should be aware of remaining hidden files after MySQL has been uninstalled for the first time. In order to remove them all (and make one successful installation), we should:

  1. Make hidden files visible on your computer (instructions)
  2. Delete all files related to MySQL after choosing uninstalling of the MySQL (I had to check C://ProgramData hidden folder)
  3. Try a new installation

I think that during the first installation, I didn’t have all required dependencies on the computer (for example Python) and the installation failed. After installing it, uninstalling the MySQL, and taking steps from above, I finally managed to run it successfully :)

I hope this could help someone! :)

answered Dec 11, 2020 at 11:01

Katarina Ivanic's user avatar

This solved it for me (MAC OS)

  1. Open MySQL from System Preferences > MySQL
  2. Click ‘Stop MySQL Server’ if the server is running
  3. Select ‘Initialize Database’
  4. Type your new password.
  5. Choose ‘Use legacy password’
  6. Start the Server again.
  7. Now connect the MySQL Workbench

AroniasPrenovost's user avatar

answered May 18, 2019 at 9:25

Peta's user avatar

PetaPeta

2281 silver badge13 bronze badges

Not able to connect to the database server on MySQL Workbench? Solve this error with a simple ALTER query.

I think last week I published an article on how to install MySQL Workbench on Ubuntu 20.04. After a couple of days, someone sent me an email.

And the email was from one of our readers, and she wrote to me, “I was able to install MySQL Workbench on my Ubuntu system, and once I try to log into a local database, I get the pop-up with the following error with the list of steps for troubleshooting.”

Your connection attempt failed for user ‘root’ to the MySQL server at localhost:3306: Access denied for user “root”@”localhost” (using password: YES)

Please:

  1. Check that MySQL is running on address localhost.
  2. Check that MySQL is reachable on port 3306 (note: 3306 is the default, but this can be changed).
  3. Check the user root has rights to connect to localhost from your address (MySQL rights define what clients can connect to the server and from which machines).
  4. Make sure you are both providing a password if needed and using the correct password for localhost connecting from the host address you’re connecting from”.

I tried everything, but the problem persists.

This problem is no longer new to me, so I replied to her with the steps to resolve the error.

If you are also getting a similar kind of error, then you don’t need to look any further because in this article, we will see how to resolve that error.

Steps to Solve Database Connection

I believe you are in a hurry to solve this problem, so first we will see how to resolve the cannot connect to database server error, and then we will explain to you why this error occurred.

Step 01Login to MySQL with the root User

You need to login to MySQL as the root user to make changes. To do that, open a terminal window using Ctrl + Alt + T and run the following command:

$ sudo mysql -u root

Step 2 Alter or Change the Password Mechanism

By default, MySQL uses socket authentication to authenticate a user, so we need to pass the below command to change the password mechanism.

mysql> ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'password';
  • ALTER USER: MySQL command to modify user details
  • 'root'@'localhost': Specifying root information along with the host
  • IDENTIFIED WITH mysql_native_password BY: Change the password socket_auth mechanism to mysql_native_password
  • 'password': Over here, pass the new passphrase/password
Output

Query OK, 0 rows affected (0.00 sec)

Step 3Run MySQL Workbench

The final step is to run and check whether the error is resolved. To run MySQL Workbench, press the super key and search for ‘MySQL Workbench’.

Go to the MySQL Connections options and click on “Local Instance” to connect.

Cannot connect to database server mysql workbench: Login Prompt
Run MySQL Workbench without any error

If it’s asking for your password, enter the password you have created from the above steps.

I have already mentioned that we’ll explain to you why this error occurs. There are many possibilities for the following error, but this error can be resolved using the above steps.

By default, MySQL uses socket_authentication to authenticate root users without requiring passwords. Now the question is, “What is socket_authentication?” It is the mechanism through which the user does not need to enter a password to log in.

And when you try to access your database through the MySQL Workbench, you end up with the above error. To resolve that error, we have to use the traditional method to log in, and you can even disable it permanently.

Wrapping Up

That’s all for how to resolve can not connect to a database server (MySQL Workbench).

Read this :- Completely uninstall MySQL-server in 3 simple steps

If you are stuck somewhere, please feel free to comment, and if you like the article or if I missed something, please let me know to make this article even more amazing.

profile

A man with a tech effusive who has explored some of the amazing technology stuff and is exploring more. While moving towards, I had a chance to work on Android development, Linux, AWS, and DevOps with several open-source tools.

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.

Не могли бы вы помочь мне решить эту проблему?

Когда я пытаюсь щелкнуть «базу данных запросов» в меню базы данных в Workbench Mysql. это дает мне ошибку:

Cannot Connect to Database Server

Your connection attempt failed for user 'root' from your host to server at 
127.0.0.1:3306:Can't connect to mysql server on '127.0.0.1'(10061)

Please:

 1. Check that mysql is running on server 127.0.0.1
 2. Check that mysql is running on port 3306 (note: 3306 is the default, but this can 
    be changed)
 3. Check the root has rights to connect to 127.0.0.1 from your address (mysql rights 
    define what clients can connect to the server and from which machines) 
 4. Make sure you are both providing a password if needed and using the correct 
    password for 127.0.0.1 connecting from the host address you're connecting from

4b9b3361

Ответ 1

Вероятно, проблема связана с тем, что аутентификация сокета включена для пользователя root по умолчанию, когда пароль не задан, во время обновления до ubuntu 16.04.

Решение состоит в том, чтобы вернуться к аутентификации собственного пароля. Вы можете сделать это, войдя в MySQL, используя проверку сокетов, выполнив:

sudo mysql -u root

После входа в систему:

ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'password';

который вернется к исходной (старой по умолчанию) аутентификации пароля.

Теперь используйте пароль в качестве пароля, когда это требуется MySQL.

Ответ 2

Попробуйте открыть services.msc из окна поиска в меню «Пуск» и попробуйте вручную запустить службу MySQL.

Ответ 3

Похоже, есть много причин этой ошибки.

Моя причина/решение

В моем случае причина была в том, что мой сервер был настроен на прием соединений только от localhost. Я исправил это, выполнив следующую статью: Как включить удаленный доступ к серверу баз данных MySQL?. В моем файле my.cnf не было строки skip-networking, поэтому я просто изменил строку

bind-address = 127.0.0.1

в

bind-address = 0.0.0.0

Это позволяет устанавливать соединения с любого IP, а не только с 127.0.0.1.

Затем я создал пользователя MySql, который мог подключиться с моего клиентского компьютера, выполнив следующие команды терминала:

# mysql -u root -p
mysql> CREATE USER 'username'@'1.2.3.4' IDENTIFIED BY 'password';
    -> GRANT ALL PRIVILEGES ON *.* TO 'username'@'1.2.3.4' WITH GRANT OPTION;
    -> q

где 1.2.3.4 — это IP-адрес клиента, с которого вы пытаетесь подключиться. Если у вас действительно есть проблемы, вы можете использовать '%' вместо '1.2.3.4', чтобы позволить пользователю подключаться с любого IP.

Другие причины

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

Ответ 4

Вы пытались определить, является ли это проблемой с Workbench или общей проблемой соединения? Попробуйте следующее:

  • Откройте терминал
  • Тип mysql -u root -p -h 127.0.0.1 -P 3306
  • Если вы можете подключиться успешно, вы увидите приглашение mysql после ввода пароля (введите quit и Enter there to exit).

Сообщите, как это сработало.

Ответ 5

У меня была похожая проблема в Mac OS, и я смог ее исправить следующим образом:

Из терминала запустите:

mysql -u root -p -h 127.0.0.1 -P 3306

Затем меня попросили ввести пароль. Я просто нажал Enter, так как пароль не был установлен.

Я получил сообщение следующим образом:

Добро пожаловать на монитор MySQL. Команды заканчиваются на; или g. Ваш идентификатор соединения MySQL — 181. Версия сервера: 8.0.11 Homebrew.

Если вам удалось войти в mysql>, выполните следующую команду:

ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'password';

Вы должны получить сообщение, подобное этому:

Запрос в порядке, затронуто 0 строк (0,19 с)

Теперь ваш пароль — » пароль «, а имя пользователя — » root «.

Удачного кодирования :)

Ответ 6

Мне пришлось запустить Workbench в качестве администратора. По-видимому, у него не было необходимых разрешений для подключения к процессу сервера базы данных localhost.

Щелкните правой кнопкой мыши ярлык Workbench и выберите Run as Administrator. В окне свойств ярлыка вы можете нажать «Дополнительно» и поставить галочку рядом с надписью «Запуск от имени администратора», чтобы всегда запускать Workbench с правами администратора.

Ответ 7

Я некоторое время боролся с этой проблемой и делал несколько переустановок MySQL, прежде чем обнаруживать это.

Я знаю, что сервер MySQL работал нормально, потому что я мог получить доступ ко всей моей БД с помощью командной строки.

Надеюсь, это сработает для вас.

В MySQL Workbench (5.2.47 CE)

нажмите Экземпляры сервера Mange (нижний правый угол)

нажмите Соединение

в поле Соединение выберите:

Локальный экземпляр ($ ServerName) — [email protected]: 3306 ‘<‘ Стандартный (TCP/IP) >

нажмите Изменить выбранные…

под Параметры, Имя хоста измените localhost или 127.0.0.1 на имя NetBIOS

нажмите Проверить соединение

Если это сработает для вас, отлично. Если имя хоста не изменилось, то оно было.

Ответ 8

Ошибка возникает из-за того, что сервер mysql не запускается на вашем компьютере. Вы должны запустить его вручную. Выполните следующие действия:

  • Загрузите и установите сервер Wamp в соответствии со своей битовой версией (32 бит или 64 бит) на вашем компьютере (http://wampserver-64bit.en.softonic.com/). позволяет загружать сервер Wamp на 64-разрядный.

  • Как только вы его установили, вы можете дважды щелкнуть и запустить его.. (вы можете увидеть значок в правой руке панели задач. Возможно, он скрыт. Вы можете щелкнуть стрелку, которая показывает вам скрыть запуск приложений). Нажмите на значок и перейдите в Mysql

  • Затем перейдите в Сервис, и там вы можете найти Начать/возобновлять службы.

  • И теперь это делается. Откройте рабочий стол mysql и увидите. Он будет работать.

Ответ 9

Запустите команду ALTER USER. Обязательно смените пароль на надежный пароль по вашему выбору.

  1. sudo mysql # Войдите в MySQL

  2. Запустите приведенную ниже команду

    ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'password';
    

Теперь вы можете получить к нему доступ, используя новый пароль.

Ref: https://www.digitalocean.com/community/tutorials/how-to-install-mysql-on-ubuntu-18-04

Ответ 10

Чтобы быть в курсе последних версий и более поздних посетителей:

В настоящее время я работаю над win7 64bit с различными инструментами, включая python 2.7.4, как необходимое условие для google android…

Когда я обновил с WB 6.0.8-win32 до верхних версий, чтобы иметь 64-битную производительность, у меня были некоторые проблемы, например, на 6.3.5-winx64. У меня была ошибка в представлении деталей таблиц (неупорядоченное представление), что привело к понижению до 6.2.5-winx64.

В качестве пользователя GUI легкие функции пересылки вперед/назад и относительные элементы сервера db работали хорошо, но когда мы пытаемся Database>Connect to Database, у нас будет Not connected и будет ошибка python, если мы попытаемся выполнить запрос, однако DB серверная служба абсолютно запущена и работает хорошо, и эта проблема не с сервера, а с рабочего места. Чтобы решить эту проблему, мы должны использовать Query>Reconnect to Server, чтобы явно выбрать соединение с БД, а затем почти все выглядит хорошо (это может быть связано с моими множественными соединениями db, и я не смог найти какое-то решение для определения подключения по умолчанию в рабочем столе).

В качестве примечания: потому что я использую последнюю версию Xampp (даже в зависимостях от linux:)), в последнее время Xampp использует mariadb 10 вместо mysql 5.x приводит к тому, что версия файла mysql равна 10, может вызвать некоторые проблемы, такие как переадресация разработка процедур, которые могут быть решены с помощью mysql_upgrade.exe, но при попытке проверить соединение db wb сообщит о неправильной версии, однако это не критично и работает хорошо.

Заключение: Таким образом, иногда проблемы с подключением db в workbench могут быть связаны с самим собой, а не с сервером (если у вас нет других проблем с подключением к db).

Ответ 11

Причина была в том, что я пытался использовать новейший MySQL Workbench 8.x для подключения к MySQL Server 5.1 (оба работают на Windows Server 2012).

Когда я удалил MySQL Workbench 8.x и установил MySQL Workbench 6.3.10, он успешно подключился к базе данных localhost

Ответ 12

Я тоже долгое время боролся с этой проблемой.

Я прошел через этот интересный поток из форума MySQL: http://forums.mysql.com/read.php?11,11388,11388#msg-11388

Я также набрал (очевидно) некоторый хороший SO Q/A.

Похоже, что сообщение, упомянутое в вопросе «user948950», может исходить из широкого круга причин: слишком большой файл журнала, неправильные значения файла mysql.ini, пробелы в пути к файлу, проблема безопасности /acl, старые записи в реестр и т.д.

Итак, после попытки за 3 часа исправить это… Я отказался и решил сделать старую старую переустановку.

Здесь этот пост из (снова) этот поток MySQL пришел в полезное, я цитирую:

Гэри Уильямс писал (а): Привет, ребята,

У меня была точно такая же проблема, и вот как я ее работаю для меня, начиная с нерабочей установки.

  • Остановите службу Windows для любой существующей установки mysql.

  • Удалите Mysql.

Как и при большинстве удалений, старые файлы остаются позади. Если ваш каталог это C:mysqletc, то удалите файлы innob и т.д., но оставьте сами каталоги, а также любые существующие базы данных в «данных». Если ваш каталог — C:Program Filesetc, удалите все mysql каталоги.

  • Теперь стоит запустить regedit, чтобы удалить старые записи реестра, а также удалить. Если нет, удалите их.

  • Хорошо использовать новый .msi-установщик (только для основных файлов), однако….

  • Не используйте свой путь установки по умолчанию! Некоторые гении устанавливают путь с пробелами в нем! Выберите пользовательскую установку и выберите разумный путь, т.е. C:mysql (примечание от Adrien: C:mysqldata для… данных)

  • Не следует изменять параметры безопасности. Снимите флажок в соответствующем поле, и установка завершится без установки root пароль.

Думаю, я все вспомнил.

Удачи.

Гэри

Я столкнулся с проблемами, когда просто копировал/вставлял базы данных, которые у меня были в предыдущем каталоге данных, в новый. Поэтому работа, которую я нашел, заключалась в том, чтобы экспортировать каждую базу данных (я знаю… много веселья), а затем повторно импортировать их по одному.

FYI: я использовал следующую команду для импорта C:/<MySQLInstallDir>/My SQL Server x.x/bin/mysql -u root -p <dbName> < "<dirPathOfDump><dumpName>.sql", например C:/mysql/MySQL Server 5.6/bin/mysql -u root -p mySupaCoolDb < "C:mySupaCoolDbDump20130901.sql"

Ответ 13

Я был в подобных ситуациях до и в прошлый раз, когда обнаружил, что это проблема с выпуском Windows (не уверен). На этот раз я открыл Workbench MySQL и не нашел подключения к моей локальной базе данных. Я не вижу свои таблицы, но вчера я мог подключиться к базе данных.

Я обнаружил, что моя причина в том, что после того, как мой компьютер снова сработает и снова проснется, служба mysql не работает.
Мое решение: перезапустите службу с именем «mysql» и перезапустите верстак. Перезапуск службы занимает некоторое время, но он работает.

Ответ 14

Моя проблема заключалась в том, что сервер MySQL фактически не был установлен. Я запустил MySQL Installer, но он не установил сервер MySQL.

Я перезапущу установщика, нажмите «Добавить», а затем добавил сервер MySQL в список. Теперь он отлично работает.

Ответ 15

В моем случае я только что установил MySQL Workbench, но после удаления MySQL Workbench и установки установщика MySQL он одинаков как для 32-разрядных, так и для 64-разрядных, после чего он работает как чудо. Надеюсь, это может быть полезно.

  • Mysql workbench ошибка 1452
  • Mysql workbench ошибка 1064
  • Mysql server ошибка установки
  • Mysql server ошибка при установке
  • Mysql num rows ошибка