Forums

External database connection

Hi,

I have a Hacker plan on PythonAnywhere, and I need to access my MySQL database. I followed the instructions from the Python code section, using mysql.connector instead of MySQLdb.

Here's my code:

def open_connection():
connection = None
try
    with SSHTunnelForwarder(
        ('ssh.pythonanywhere.com'),
        ssh_username='ingnavas', ssh_password='my password PythonAnywhere website',
        remote_bind_address=('ingnavas.mysql.pythonanywhere-services.com', 3306)
    ) as tunnel:
        print('ok after tunneling')
        connection = mysql.connector.connect(
            host='127.0.0.1', 
            port=tunnel.local_bind_port,
            database='ingnavas$comseg',
            user='ingnavas',
            password='my mySQL database password')
    print('pass try connection')
        if connection.is_connected():
            cursor = connection.cursor()
            connected_status = '0'
            return connection, cursor, connected_status
except (Exception,Error) as error:
    connected_state = error
    return None, None, connected_status

when execute this print

ok after tunneling'

When I execute the code, it prints:

ok after tunneling

but it doesn't print:

pass try connection

(I put this prints to debbuging)

The program then stops without any response.

Do I need to make any additional configurations for external access?

Is the indentation of your code correct? In the snippet you shared, print('pass try connection') is improperly indented. You should also print the error in the except block to see what's going on.

Hi, thanks for yor answer. The problem not was the indentation. I change from mysql.connector to MySQLdb library and it is working rigth now.

OK, glad to hear you got it working!