PyMySQL can't connect to MySQL on localhost

不想你离开。 提交于 2019-12-17 09:22:34

问题


I'm trying to connect to MySQL on localhost using PyMySQL:

import pymysql
conn = pymysql.connect(db='base', user='root', passwd='pwd', host='localhost')

but (both on Python 2.7 and Python 3.2) I get the error:

socket.error: [Errno 111] Connection refused

pymysql.err.OperationalError: (2003, "Can't connect to MySQL server on 'localhost' (111)")

I'm sure mysqld is running because I can connect using mysql command or phpMyAdmin. Moreover, I can connect using MySQLdb on Python 2 with nearly the same code:

import MySQLdb
conn = MySQLdb.connect(db='base', user='root', passwd='pwd', host='localhost')

It seems that the problem is on PyMySQL side rather than MySQL but I have no idea how to solve it.


回答1:


Two guesses:

  1. Run mysqladmin variables | grep socket to get where the socket is located, and try setting up a connection like so:

    pymysql.connect(db='base', user='root', passwd='pwd', unix_socket="/tmp/mysql.sock")
    
  2. Run mysqladmin variables | grep port and verify that the port is 3306. If not, you can set the port manually like so:

    pymysql.connect(db='base', user='root', passwd='pwd', host='localhost', port=XXXX)
    



回答2:


Seems like changing localhost to 127.0.0.1 fixes the error, at least in my configuration. If it doesn't, I would look for errors in tcp sockets connection and, of course, post it as a bug in pymysql bugtrack.




回答3:


I solved the issue by replacing localhost with 127.0.0.1 and changing the password to my MYSQL database password as shown below;

conn = pymysql.connect(
    host = '127.0.0.1',
    port = 3306,
    user = 'root',
    passwd = 'XXXXXXXXX',
    db = 'mysql'
)



回答4:


I met the same question and my solution is as follows:

  1. Run ssh -fN -L 3307:mysql_host:3306 ssh_user@ssh_host in my terminal.
  2. Then input your ssh password
  3. conn = pymysql.connect(db='base', user='root', passwd='pwd', host='localhost')

This error occurs because database does not support link directly.




回答5:


I asked why socket worked but not TCP and the answer was that bind-address in /etc/my.cnf was not set correctly. This could be your problem too since the socket methods works just fine but the TCP one does not.




回答6:


You need to add the port to the connection as well. Try this and it works fine.

pymysql(Module Name).connect(host="localhost", user="root", passwd="root", port=8889, db="db_name")


来源:https://stackoverflow.com/questions/6885164/pymysql-cant-connect-to-mysql-on-localhost

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