首页 > 解决方案 > 查询期间丢失与 MySQL 服务器的连接 - Python 3.x - pymysql

问题描述

我正在尝试连接到服务器以使用 python 中的 pymysql 库从其中一个数据库中获取详细信息。但我不断收到同样的错误,我不知道为什么。我对 Python 很陌生,希望有人能在这里帮助我。

我尝试在这里查看帖子,但不是很有帮助。

这是我的代码。

import pymysql
print("Connecting mysql")
connection = pymysql.connect(host=A.B.C.D,user='admin',password='admin',db='MY_DB',port=ABCD)

这是我得到的错误

       Connecting mysql
   Traceback (most recent call last):
  File "C:\Users\anon\AppData\Local\Programs\Python\Python35\lib\site-packages\pymysql\connections.py", line 690, in _read_bytes
    data = self._rfile.read(num_bytes)
  File "C:\Users\anon\AppData\Local\Programs\Python\Python35\lib\socket.py", line 571, in readinto
    return self._sock.recv_into(b)
ConnectionResetError: [WinError 10054] An existing connection was forcibly closed by the remote host

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:/Users/anon/PycharmProjects/labelFetch/getlabel.py", line 3, in <module>
    connection = pymysql.connect(host='172.16.137.50',user='qaadmin',password='qaadmin',db='QA_INTRANET',port=1433)
  File "C:\Users\anon\AppData\Local\Programs\Python\Python35\lib\site-packages\pymysql\__init__.py", line 94, in Connect
    return Connection(*args, **kwargs)
  File "C:\Users\anon\AppData\Local\Programs\Python\Python35\lib\site-packages\pymysql\connections.py", line 327, in __init__
    self.connect()
  File "C:\Users\anon\AppData\Local\Programs\Python\Python35\lib\site-packages\pymysql\connections.py", line 597, in connect
    self._get_server_information()
  File "C:\Users\anon\AppData\Local\Programs\Python\Python35\lib\site-packages\pymysql\connections.py", line 966, in _get_server_information
    packet = self._read_packet()
  File "C:\Users\anon\AppData\Local\Programs\Python\Python35\lib\site-packages\pymysql\connections.py", line 656, in _read_packet
    packet_header = self._read_bytes(4)
  File "C:\Users\anon\AppData\Local\Programs\Python\Python35\lib\site-packages\pymysql\connections.py", line 698, in _read_bytes
    "Lost connection to MySQL server during query (%s)" % (e,))
pymysql.err.OperationalError: (2013, 'Lost connection to MySQL server during query ([WinError 10054] An existing connection was forcibly closed by the remote host)')

标签: python-3.xpymysql

解决方案


您可能想尝试使用pymssql而不是 pymysql。

我遇到了同样的错误,但我的原因是我的数据库不是 MySQL 而是 Microsoft SQL 数据库。然后使用适当的库(pymssql)解决了这个问题。


推荐阅读