0

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()
smchae
  • 1,035
  • 3
  • 17
  • 39
  • Can you double check the indentation in the code snippet you've pasted? It looks like you're leaving the `with sshtunnel` context which would close the connection – Peter Gibson Apr 20 '17 at 02:28
  • @PeterGibson I do not understand the problem with indentation. Could you please explain more details please? Because what I understand from the code above is that when `with sshtunnel` part and `as tunnel` part is done, `cur = db.cursor()` is executed. – smchae Apr 20 '17 at 02:37
  • `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. – tdelaney Apr 20 '17 at 02:42
  • Indent all of the db lines and it should work. – tdelaney Apr 20 '17 at 02:42
  • @Peter Gibson @tdelaney Thank you so much! It works! One more question is that do I need to close ssh connection? If I do, how do I do this? I know db has been closed with `db.close()` but i am not familiar with `sshtunnel.SSHTunnelForwarder` – smchae Apr 20 '17 at 02:45

0 Answers0