报错信息具体如下:
mysql -uroot -p
ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)
若是在终端中登陆MySQL,可如此轻松解决:
sudo mysql -uroot -p
若是使用后端服务器的python脚本出现无法登陆MySQL的问题(无法直接加上sudo),则需如此解决:
查看MySQL用户列表登陆主机权限:
mysql> use mysql;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A
Database changed
mysql> select host,user from user;
+-----------+------------------+
| host | user |
+-----------+------------------+
| localhost | debian-sys-maint |
| localhost | mysql.infoschema |
| localhost | mysql.session |
| localhost | mysql.sys |
| localhost | root |
+-----------+------------------+
5 rows in set (0.00 sec)
修改mysqld.cnf文件:
cd /etc/mysql/mysql.conf.d
ls
mysql.cnf mysqld.cnf
sudo vim mysqld.cnf
具体做如下修改:
# Instead of skip-networking the default is now to listen only on
# localhost which is more compatible and is not less secure.
#bind-address = 127.0.0.1
#mysqlx-bind-address= 127.0.0.1
bind-address = 0.0.0.0
mysqlx-bind-address = 0.0.0.0
即将两个IP都改为0.0.0.0。
重启MySQL服务:
sudo systemctl restart mysql.service
创建'root'@'%'账户,并再次查看当前MySQL用户列表登陆主机权限:
mysql> use mysql;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A
Database changed
mysql> create user 'root'@'%' identified by 'your_password';
Query OK, 0 rows affected (0.02 sec)
mysql> select user,host from user;
+------------------+-----------+
| user | host |
+------------------+-----------+
| root | % |
| debian-sys-maint | localhost |
| mysql.infoschema | localhost |
| mysql.session | localhost |
| mysql.sys | localhost |
| root | localhost |
+------------------+-----------+
6 rows in set (0.00 sec)
为账户'root'@'%'赋予权限并生效:
mysql> grant all privileges on *.* to 'root'@'%';
Query OK, 0 rows affected (0.01 sec)
mysql> flush privileges;
Query OK, 0 rows affected (0.01 sec)
查看当前IP:
ifconfig
eth0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500
inet 172.25.88.77 netmask 255.255.240.0 broadcast 172.25.95.255
inet6 fe80::215:5dff:fe03:332 prefixlen 64 scopeid 0x20<link>
ether 00:15:5d:03:03:32 txqueuelen 1000 (Ethernet)
RX packets 4568 bytes 14020525 (14.0 MB)
RX errors 0 dropped 0 overruns 0 frame 0
TX packets 2616 bytes 2698995 (2.6 MB)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0
lo: flags=73<UP,LOOPBACK,RUNNING> mtu 65536
inet 127.0.0.1 netmask 255.0.0.0
inet6 ::1 prefixlen 128 scopeid 0x10<host>
loop txqueuelen 1000 (Local Loopback)
RX packets 938 bytes 6784064 (6.7 MB)
RX errors 0 dropped 0 overruns 0 frame 0
TX packets 938 bytes 6784064 (6.7 MB)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0
找到对应的python代码中链接MySQL的部分:
(修改为使用上面查找到的IP登陆连接到MySQL数据库)
原代码:pymysql.connect(host="localhost",user='root',password='your_password',database='mysql',charset='utf8')
改为:pymysql.connect(host="172.25.88.77",user='root',password='your_password',database='mysql',charset='utf8')
至此,便能成功登陆上MySQL!