首页 > 解决方案 > 使用 pymysql 连接到 cloudcluster mysql 的问题

问题描述

我有以下代码可以连接到我的云主机(注 X 是实际凭据的占位符)。是的,我环顾四周,没有找到可用的答案

import pymysql

try:
    db = pymysql.connect(host='xxxxxxxx', user='xxxxxx', 
                         password='xxxxxx', database='xxxxxxxx',
                         port=xx, connect_timeout=60)
except Exception as e:
    print(f'Failed connection {str(e)}')

我收到以下错误

Traceback (most recent call last):
  File "C:\Users\THEMBEKILE\Desktop\Projects\Cafe Nalla1\dbcreatetable.py", line 10, in <module>
    database="xxxxxxxx", port=xxxxx, connect_timeout=60)
  File "C:\Users\THEMBEKILE\AppData\Local\Programs\Python\Python36\lib\site-packages\pymysql\__init__.py", line 94, in Connect
    return Connection(*args, **kwargs)
  File "C:\Users\THEMBEKILE\AppData\Local\Programs\Python\Python36\lib\site-packages\pymysql\connections.py", line 325, in __init__
    self.connect()
  File "C:\Users\THEMBEKILE\AppData\Local\Programs\Python\Python36\lib\site-packages\pymysql\connections.py", line 598, in connect
    self._get_server_information()
  File "C:\Users\THEMBEKILE\AppData\Local\Programs\Python\Python36\lib\site-packages\pymysql\connections.py", line 976, in _get_server_information
    packet = self._read_packet()
  File "C:\Users\THEMBEKILE\AppData\Local\Programs\Python\Python36\lib\site-packages\pymysql\connections.py", line 657, in _read_packet
    packet_header = self._read_bytes(4)
  File "C:\Users\THEMBEKILE\AppData\Local\Programs\Python\Python36\lib\site-packages\pymysql\connections.py", line 708, in _read_bytes
    CR.CR_SERVER_LOST, "Lost connection to MySQL server during query")
pymysql.err.OperationalError: (2013, 'Lost connection to MySQL server during query')

请注意:所有凭据都是正确的,我已将这个确切的代码用于早期应用程序,只是不同的数据库和相同的供应商,一切正常。

我可以使用 cmd 和此命令连接到数据库。这让我更加困惑: Sqlcmd -S xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx -d xxxxxxxxxxx -U xxxxxxxxxx -P xxxxxxxx

任何有关此事的帮助将不胜感激。

标签: pythonpymysql

解决方案


在做了一些研究后,我发现了我的问题。我用我之前做过的 cloudcluster 打开了一个 SQL 服务器实例,并成功地连接到了 python 和 pymysql 模块。唯一的区别是 sql 类型。

以前我打开的是 MySQL Sever 实例而不是 SQL Server。要连接到 SQL Server,您将使用 pyodbc,而要连接到 MySQL 服务器,您将使用 pymysql 或 mysql.connector。

您无法使用带有 python 的 MySQL 工具连接到 SQL 实例

即使使用命令行连接到 SQL 实例,您也将使用该sqlcmd命令并连接到 MySQL 服务器您将使用该mysql命令。


推荐阅读