Connect to remote MySQL via Python

时光总嘲笑我的痴心妄想 提交于 2020-01-04 16:38:30

问题


I have installed MySQL on a remote server. I also created some databases with some tables in them, all via SSH.

I have created the following users:

CREATE USER 'myname'@'localhost' IDENTIFIED BY 'mypassword';
CREATE USER 'remotMe'@'myIP' IDENTIFIED BY 'mypassword';

GRANT PRIVILEGES * . * TO 'myname'@'localhost';
GRANT PRIVILEGES * . * TO 'remoteMe'@'myIP';

Now, I would like to connect to this MySQL server via Python. I have installed PyMySQL. I am trying out the following code:

import pymysql
conn = pymysql.connect(host='ServerIP', port=3306, user='remoteMe', passwd='mypassword', db='myDB') 

But this gives me a connection refused error. Do I need to configure something else to make this work?


回答1:


It's likely MySQL is bound to localhost. Assuming you're using a Linux machine:

On your remote machine, edit /etc/mysql/my.cnf

Find bind-address=127.0.0.1, edit it to bind-address=0.0.0.0, or just remove the line.

Restart MySQL

Read more: http://dev.mysql.com/doc/refman/5.1/en/server-options.html#option_mysqld_bind-address




回答2:


The connection refused error message actual means that it was not possible to open a TCP socket. The server refused the connection. This is not related to the authentication or user permissions since the refusal happens on the OS level before the MySQL server is involved. Possible causes are:

  • the MySQL server is bound to localhost only → set the listening address to the servers real IP address or 0.0.0.0 in mysql.conf
  • there is a firewall in between → reconfigure/deactivate the firewall
  • your connection details (server/port) are wrong → check them again


来源:https://stackoverflow.com/questions/28851765/connect-to-remote-mysql-via-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!