首页 > 解决方案 > google-collab:如何在 Google Collab 中连接到 pymysql?

问题描述

在 google-colab 中,我尝试了这个:

!pip install pymysql
import pymysql
cnx = {'host':'localhost','username':'root','pwd':'','db':'test'}
connection = pymysql.connect(cnx['host'], cnx['username'], cnx['pwd'], cnx['db'])
connection.close()

面临的错误:

---------------------------------------------------------------------------
ConnectionRefusedError                    Traceback (most recent call last)
/usr/local/lib/python3.6/dist-packages/pymysql/connections.py in connect(self, sock)
    582                                 (self.host, self.port), self.connect_timeout,
--> 583                                 **kwargs)
    584                             break

5 frames
ConnectionRefusedError: [Errno 111] Connection refused

During handling of the above exception, another exception occurred:

OperationalError                          Traceback (most recent call last)
/usr/local/lib/python3.6/dist-packages/pymysql/connections.py in connect(self, sock)
    628                 exc.traceback = traceback.format_exc()
    629                 if DEBUG: print(exc.traceback)
--> 630                 raise exc
    631 
    632             # If e is neither DatabaseError or IOError, It's a bug.

OperationalError: (2003, "Can't connect to MySQL server on 'localhost' ([Errno 111] Connection refused)")

尝试了 的建议127.0.0.1,但没有运气,然后看到这个,尝试:

connection = pymysql.connect(cnx['host'], cnx['username'], cnx['pwd'], cnx['db'],port=3306)

还是一样connection refused。甚至可以从 google-colab 连接到本地数据库吗?如果是这样,还有什么错误我有什么选择?

数据库详细信息(从 运行XAMPP):

MySQL Version                 : 10.1.13-MariaDB
Host                          : localhost
User                          : root
Port                          : 3306
Server Default Charset        : latin1

文件状态my.inibind-address="127.0.0.1"和密码在文件中被注释掉# password = your_password。在 SQLYog 数据库中运行。

标签: pythonmysqlgoogle-colaboratorypymysql

解决方案


推荐阅读