Forums

Unable to connect to MySQL database from PA, can connect remotely

I've been connecting to my database remotely without issue. I open an ssh tunnel, then connect with mysql.connector. I've now moved my code to PythonAnywhere and the same code with the same credentials now can't connect. The connection is made with a decorator:

def connect_to_database(original_func):
"""Decorator function to connect to the database, run the function, and then close the connection
Args:
    original_func (function): Function to be wrapped
"""

def make_connection(*args, **kwargs):
    results = None
    try:
        # print("Connecting to database...")
        db = mysql.connector.connect(
            user="suspiciousleaf",
            password=db_password,
            host="localhost",
            port=3306,
            database=database,
            use_pure=True,
        )
        cursor = db.cursor()
        results = original_func(db, cursor, *args, **kwargs)

    except Exception as e:
        print(f"An error occurred: {str(e)}")
    finally:
        if "cursor" in locals() and cursor:
            cursor.close()
        if "db" in locals() and db:
            db.close()
        # print("Database connection closed")
        if results is not None:
            return results

return make_connection

Remotely this works fine, but when I run the code on PA I get An error occurred: 2003: Can't connect to MySQL server on 'localhost:3306' (111 Connection refused). I've tried using localhost and 127.0.0.1 for the host, both give the same results.

The ssh command I'm using is below, I don't think it's relevant but just in case: ssh -L 3306:suspiciousleaf.mysql.eu.pythonanywhere-services.com:3306 suspiciousleaf@ssh.eu.pythonanywhere.com

Is there anywhere obvious that I'm going wrong?

Fixed, I needed to change the host to my database host:

host="suspiciousleaf.mysql.eu.pythonanywhere-services.com"

You do not need to use the SSH tunnel on PythonAnywhere. You can just connect directly to the database.