python脚本(pymysql)未连接到localhost上的数据库

liwlm1x9  于 2021-06-21  发布在  Mysql
关注(0)|答案(2)|浏览(450)

当我使用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数据库?
另外,请记住,即使我替换 localhost127.0.0.1 我得到了完全相同的错误。而且,如果我替换 localhostlocalhost:3306 那我也是个错误( socket.gaierror: [Errno 8] nodename nor servname provided, or not known ).

6vl6ewon

6vl6ewon1#

pymysql接受port作为独立参数。试试这个:

conn = pymysql.connect(host='localhost', port=3306, user='root', passwd='', db='Work')

请参阅以下链接:pymysql

xriantvc

xriantvc2#

我只是按照下面url中给出的步骤,他们给出了连接mysqldb插件和pymysql插件的示例代码。
对我来说,mysqldb给出了输出,pymysql给出了连接错误。
https://www.a2hosting.in/kb/developer-corner/mysql/connecting-to-mysql-using-python

相关问题