Forums

Connection hangs

Hi all,

I'm trying to connect to my database from a Python script on my computer using the code found on here: https://help.pythonanywhere.com/pages/AccessingMySQLFromOutsidePythonAnywhere/

I've installed sshtunnel and sql.connector. However, when I run my script, the console just hangs, and never reaches the code where #Do stuff begins.

I bought a paid account only an hour or two ago, so maybe that's the problem?

can you connect via normal ssh? and if do you have anything interactive in your bashrc that might cause the ssh session to wait for input from you? (have you customized your bashrc at all)

Not sure how to do that... Do you mean trying to connect via ssh in terminal? (I'm using Ubuntu)

Oh I think I just connected by ssh normally! Installed openssh-server, entered 'ssh alexjayclark@ssh.pythonanywhere.com' and then my password - and looks like it connected all OK...

Have run my script again though and still hanging. This is the code I've got (have blanked out password obviously!):

import mysql.connector
import sshtunnel

sshtunnel.SSH_TIMEOUT = 5.0
sshtunnel.TUNNEL_TIMEOUT = 5.0

print('CONNECTING TO DATABASE')

with sshtunnel.SSHTunnelForwarder(
    ('ssh.pythonanywhere.com'),
    ssh_username='alexjayclark', ssh_password='XXXXX',
    remote_bind_address=('alexjayclark.mysql.pythonanywhere-services.com', 3306)
    ) as tunnel:
    connection = mysql.connector.connect(
    user='alexjayclark', password='XXXX',
    host='127.0.0.1', port=tunnel.local_bind_port,
    database='alexjayclark$default',
    )
    print("CONNECTED")
    mycursor = mydb.cursor()
    mycursor.execute("SHOW TABLES")
    for x in mycursor:
        print(x)
    connection.close()

That definitely sounds strange. From our logs it looks like you managed to log in and connect to a database about 9 hours after your forum post -- a slightly different one to the one you quote in your code above. Did you work out what the issue was?

It was a very simple fix in the end - I just switched module from mysql.connector to psmysql and my code worked instantly... Any ideas what that could have been about?

Glad you found a solution! I've no idea why that might have fixed it, though -- mysql.connector certainly normally works.

Having the same issue here.

Have you tried switching from mysqlconnector to pymysql like alexjayclark did?

Oh nice, thanks for the tip I did the change and it is now working with pymysql

Thanks for confirming that!

same error and fix for me - shame that mysql.connector which you use in your example does not work anymore

Where did you find the example that you mention? The official docs use the mysqlclient package, and the only example, using mysql.connector that I can see is @alexjayclark's post above, which is from quite some time ago.