我在通过pymysql通过SSH连接到Ubuntu 18.04 LTS服务器上的远程MySQL数据库时遇到问题。但是,使用MySQL Workbench通过SSH连接到同一服务器和数据库不会产生任何问题-无论查询如何。
我尝试将wait_timeout
和interactive_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")
是否有什么我应该调查/尝试的才能使上面的代码起作用?任何建议都非常感谢!