当我使用php时,只需在php脚本中编写以下行,就可以连接到本地主机上的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
).
2条答案
按热度按时间6vl6ewon1#
pymysql接受port作为独立参数。试试这个:
请参阅以下链接:pymysql
xriantvc2#
我只是按照下面url中给出的步骤,他们给出了连接mysqldb插件和pymysql插件的示例代码。
对我来说,mysqldb给出了输出,pymysql给出了连接错误。
https://www.a2hosting.in/kb/developer-corner/mysql/connecting-to-mysql-using-python