0

I am trying to connect to my pythonanywhere DB from a local python file, using the following code.

import MySQLdb, sshtunnel
sshtunnel.SSH_TIMEOUT = 5.0
sshtunnel.TUNNEL_TIMEOUT = 5.0

queryAdd = ("INSERT INTO `****$geo***`.O***"
               "(name, address) "
               "VALUES (%s, %s)")

with sshtunnel.SSHTunnelForwarder(
    ('ssh.pythonanywhere.com'),
    ssh_username='*******', ssh_password='*******',
    remote_bind_address=('*****.mysql.pythonanywhere-services.com', 3306)
) as tunnel:
    connection = MySQLdb.connect(
        user='******',
        passwd='********',
        host='127.0.0.1', port=tunnel.local_bind_port,
        db='****$geo******',
        )

cursor = connection.cursor()    

for row in dl:
    tup=(row['name'],row['address'])
    cursor.execute(queryAdd, tup)
    connection.commit()

However, as soon as the code is run, I get the following error:

MySQLdb._exceptions.OperationalError: (2013, 'Lost connection to MySQL server during query')

There is no delay between creating the connection and running the query. What am I doing wrong?

1 Answer 1

0

You need to do everything inside your with block as the tunnel is gone when you go outside of the context.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks @Filip! It worked.

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.