OperationalError("MySQL Connection not available.")

I'm receiving this error when trying to just run a simple query on my database.

My code is as follows (I left the first part default but I actually have it filled out with my information on my python script):

import mysql.connector
import sshtunnel

sshtunnel.SSH_TIMEOUT = 5.0
sshtunnel.TUNNEL_TIMEOUT = 5.0

with sshtunnel.SSHTunnelForwarder(
('your SSH hostname'),
ssh_username='your PythonAnywhere username', ssh_password='the password you use to log in to the PythonAnywhere website',
remote_bind_address=('your PythonAnywhere database hostname, eg.', 3306)
) as tunnel:
connection = mysql.connector.connect(
    user='your PythonAnywhere username', password='your PythonAnywhere database password',
    host='', port=tunnel.local_bind_port,
    database='your database name, eg yourusername$mydatabase',
cursor = connection.cursor()
cursor.execute("select * from semesters")

for i in cursor:


I just take the default code and I run a simple execute command from mysql.connector. However I get the error in the title and I'm not sure what I am doing wrong. Here is the full error message:

Traceback (most recent call last):
 File "C:\Users\Jaden\python_datebase\", line 17, in <module>
 cursor = connection.cursor()
 File "E:\Python 3.9\lib\site-packages\mysql\connector\", line 809, in cursor
 raise errors.OperationalError("MySQL Connection not available.")
mysql.connector.errors.OperationalError: MySQL Connection not available.

Again, in my actual code, I do not have the fill in the blanks in the sshtunnel and connection parts left as default. Any help would be appreciated.

Are you able to connect to the PythonAnywhere account using ssh and the same set of credentials?

I haven't looked into this @fjl. I was only wondering as I wanted to run simple commands on my python script on VS Code.

It looks like the formatting was dropped in the code that you posted; was the line

cursor = connection.cursor()

...indented so that it was within the "with" block? If not, that would be the problem -- the SSH tunnel through to the MySQL server is closed when you exit that block.