The solution to “Can’t connect to MySQL server on xxxxx

Jenny
2 min readDec 24, 2020

When I want to build connections between database and Python programs with SQLAlchemy on Google Colab, it occurs errors saying: (mysql.connector.errors.InterfaceError) 2003: Can’t connect to MySQL server on ‘localhost:3306’ (111 Connection refused) and Can’t connect to MySQL server on ‘localhost:3306’ [Errno 99] Cannot assign requested address.

Here’s my solution. It can also be understood as to how to allow remote MySQL database connection.

Step1. Modify bind-address

sudo vim /usr/local/etc/my.cnf

While the location of ‘bind-address’ in files is not fixed, it may summarize are:

  1. /etc/mysql/mysql.conf.d/mysqld.cnf

2. /etc/mysql/mariadb.conf.d/50-server.cnf

3. /etc/mysql/mysql.conf.d

4. /etc/mysql/mariadb.conf.d

5. /etc/mysql/my.conf

…….

In this .cnf, the mission is to replace ‘bind-address = 127.0.0.1’ by ‘bind-address = 0.0.0.0’.

First, ‘Ctrl + v’ to enter —VISUAL BLOCK — mode. Use arrow keys to select lines that need to be adjusted.

Secondly, press ‘Shift+i’ to enter insert mode. That’s to say we will comment out the line ‘bind-address = 127.0.0.1’ with ‘#’ and insert a new line ‘bind-address = 0.0.0.0’.

After done all the modifications, press ‘ESC’ to change mode, then input:

  1. :w- save files, not exit from vim

2. :w file- save the changes as a new file, not exit from vim

3. :wq- save files and exit

Before the next step, check the changes do exits in target files.

Step2. Restart MySQL Server

service mysql start

Step3. Create new users to visit remotely

mysql -u root -p

Then we will need to add a user to access the database.

grant all privileges on *.* to root@"%" identified by ".";

The above code, which you might find the most common, will lead to ERROR 1064 (42000). Because MySQL 8.0 hasn’t supported this method anymore.

The correct way is:

CREATE USER 'user'@'xx.xx.xx.xx' IDENTIFIED BY 'password';
GRANT ALL PRIVILEGES ON database’s name.* to 'user'@'xx.xxx.xx.xx' ;
FLUSH PRIVILEGES;
ALTER USER 'admin'@'%' IDENTIFIED WITH mysql_native_password BY 'password';FLUSH PRIVILEGES;

If you want the user to manage all databases, use ‘*’ as database_name.

If you want to connect from anywhere, replace ‘xx.xx.xx.xx’ with ‘%’.

For example,

--

--