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()
5
  • 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 Commented Apr 20, 2017 at 2: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. Commented Apr 20, 2017 at 2: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. Commented Apr 20, 2017 at 2:42
  • Indent all of the db lines and it should work. Commented Apr 20, 2017 at 2: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 Commented Apr 20, 2017 at 2:45

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.