pymysql连接mysql没有host,PyMySQL无法连接到本地主机上的MySQL

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.

解决方案

Two guesses:

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")

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)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值