I am trying to connect to MySQL via ssh in Python. However, it keeps giving me (2013, 'Lost connection to MySQL server during query') error.
Is this related to permission? If it does, what do I need to do? Any suggestion or advice would be appreciated!
Thank you in advance.
python.py
with sshtunnel.SSHTunnelForwarder(
(SOME_IP, 22),
ssh_username='user',
ssh_password='password',
remote_bind_address=('127.0.0.1', 3306),
local_bind_address=('127.0.0.1', 3306)
) as tunnel:
db = MySQLdb.connect(
host='127.0.0.1',
port=3306,
user="user",
passwd="password",
db="DBName",
charset='utf8'
)
cur = db.cursor()
cur.execute("SELECT * FROM DB_TABLE")
drivers = cur.fetchall()
db.close()
with sshtunnelcontext which would close the connectionwith sshtunnelpart andas tunnelpart is done,cur = db.cursor()is executed.cur = db.cursor()is outside of the context handler so SSHTunnelForwarder's__exit__has been called. I think that means that the tunnel has been closed by the time you try to use the cursor and that could be bad.db.close()but i am not familiar withsshtunnel.SSHTunnelForwarder