当我使用PHP时,我可以通过在我的php脚本中编写以下行来连接到localhost上的phpMyAdmin:
<?php
$dbServername = 'localhost';
$dbUsername = 'root';
$dbPassword = '';
$dbName = 'Work';
$conn = mysqli_connect($dbServername, $dbUsername, $dbPassword, $dbName);
?>
(此脚本的目录为/Users/User/.bitnami/stackman/machines/xampp/volumes/root/htdocs/index.php
)
在运行上述行之前,我首先激活了XAMPP
并启用了端口localhost:8080
。 phpMyAdmin
位于http://localhost:8080/phpmyadmin/
。 这可以很好地连接到数据库。
现在,在Python中我已经下载了PyMySQL
,并且我编写了以下几行来完成同样的简单任务:
import pymysql
conn = pymysql.connect(host='localhost', user='root', password='', db='Work')
(此脚本的目录为/Users/User/PycharmProjects/First/Main.py
)
然而,当我尝试运行它时(在我首次激活XAMPP
并且我启用了端口localhost:8080
之后),我收到以下错误:
Traceback (most recent call last):
File "/Users/User/Library/Python/3.6/lib/python/site-packages/pymysql/connections.py", line 920, in connect
**kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/socket.py", line 724, in create_connection
raise err
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/socket.py", line 713, in create_connection
sock.connect(sa)
ConnectionRefusedError: [Errno 61] Connection refused
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/Users/User/PycharmProjects/GCP-OCR/Main.py", line 14, in <module>
conn = pymysql.connect(host='localhost', user='root', password='', db='Work')
File "/Users/User/Library/Python/3.6/lib/python/site-packages/pymysql/__init__.py", line 90, in Connect
return Connection(*args, **kwargs)
File "/Users/User/Library/Python/3.6/lib/python/site-packages/pymysql/connections.py", line 699, in __init__
self.connect()
File "/Users/User/Library/Python/3.6/lib/python/site-packages/pymysql/connections.py", line 967, in connect
raise exc
pymysql.err.OperationalError: (2003, "Can't connect to MySQL server on 'localhost' ([Errno 61] Connection refused)")
如何修复此错误并最终将我的Python脚本连接到MySQL数据库?
此外,请注意,即使我将localhost
替换为127.0.0.1
,我也会收到完全相同的错误。此外,如果我将localhost
替换为localhost:3306
,那么我也是一个错误(socket.gaierror: [Errno 8] nodename nor servname provided, or not known
)。
答案 0 :(得分:0)
PyMySQL接受端口作为独立参数。试试这个:
conn = pymysql.connect(host='localhost', port=3306, user='root', passwd='', db='Work')
请参阅此链接:PyMySQL
答案 1 :(得分:0)
我只按照下面URL中给出的步骤进行操作,它们提供了示例代码以从MySQLdb插件和PyMySQL插件进行连接。
对我来说,MySQLdb提供输出,而PyMySQL提供连接错误,就像您得到的一样。
https://www.a2hosting.in/kb/developer-corner/mysql/connecting-to-mysql-using-python