【发布时间】:2020-01-24 13:57:03
【问题描述】:
我正在使用PyMySQL 连接到在本地主机上运行的数据库。我可以在命令行和adminer 中使用用户名/密码组合很好地访问数据库,因此这里的数据库似乎不是问题。
我的代码如下。然而,当使用host="127.0.0.1" 选项时,我得到一个OperationalError 和一个Errno 111。使用相同的代码,但通过运行Mariadb 的套接字连接是可以的。
import pymysql.cursors
from pprint import pprint
# This causes an OperationalError: (pymysql.err.OperationalError) (2003, "Can't connect to MySQL server on 'localhost' ([Errno 111] Connection refused)")
# connection = pymysql.connect(
# host="127.0.0.1",
# port=3306,
# user="root",
# password="S3kr37",
# db="my_test",
# )
# This works.
connection = pymysql.connect(
user="root",
password="S3kr37",
db="my_test",
unix_socket="/var/lib/mysql/mysql.sock"
)
try:
with connection.cursor() as cursor:
sql = "select * from MySuperTable"
cursor.execute(sql)
results = cursor.fetchall()
pprint(results)
finally:
connection.close()
我做错了什么?
PS:请注意this question 有同样的问题,但提供的解决方案是套接字。 这还不够:我想知道为什么我不能按照文档的建议使用主机名。
【问题讨论】:
标签: python mysql mariadb pymysql