如何使用pymysql修复“查询期间与MySQL服务器的连接丢失”

时间:2019-05-25 16:14:22

标签: mysql python-3.x

我在通过pymysql通过SSH连接到Ubuntu 18.04 LTS服务器上的远程MySQL数据库时遇到问题。但是,使用MySQL Workbench通过SSH连接到同一服务器和数据库不会产生任何问题-无论查询如何。

我尝试将wait_timeoutinteractive_timeout提升到MySQL服务器(最多8个小时),但没有任何反应。以下代码仅在一段时间内一次起作用:

# test.py

import pymysql
import pymysql.cursors
from sshtunnel import SSHTunnelForwarder
SSHTunnelForwarder.SSH_TIMEOUT = 200.0
SSHTunnelForwarder.TUNNEL_TIMEOUT = 200.0

with SSHTunnelForwarder(
    ('myhostname.net', 22),
    ssh_username='some_user',
    ssh_password='some_password',
    remote_bind_address=('127.0.0.1', 3306)
) as tunnel:
    conn = pymysql.connect(host='127.0.0.1', 
        port=tunnel.local_bind_port, 
        user='admin', 
        password='password', 
        db='db'
    )

这是运行上述代码失败的输出(大约是95%的时间):

Traceback (most recent call last):
  File "test.py", line 19, in <module>
    db='db'
  File "/home/alex/Desktop/the_bbc/application/venv/lib/python3.6/site-packages/pymysql/__init__.py", line 94, in Connect
    return Connection(*args, **kwargs)
  File "/home/alex/Desktop/the_bbc/application/venv/lib/python3.6/site-packages/pymysql/connections.py", line 325, in __init__
    self.connect()
  File "/home/alex/Desktop/the_bbc/application/venv/lib/python3.6/site-packages/pymysql/connections.py", line 598, in connect
    self._get_server_information()
  File "/home/alex/Desktop/the_bbc/application/venv/lib/python3.6/site-packages/pymysql/connections.py", line 975, in _get_server_information
    packet = self._read_packet()
  File "/home/alex/Desktop/the_bbc/application/venv/lib/python3.6/site-packages/pymysql/connections.py", line 657, in _read_packet
    packet_header = self._read_bytes(4)
  File "/home/alex/Desktop/the_bbc/application/venv/lib/python3.6/site-packages/pymysql/connections.py", line 707, in _read_bytes
    CR.CR_SERVER_LOST, "Lost connection to MySQL server during query")

是否有什么我应该调查/尝试的才能使上面的代码起作用?任何建议都非常感谢!

0 个答案:

没有答案