Flask connecting to MySQL database with MySQLdb

Hi, I'm currently trying to connect to the MySQL db from my local machine and planning to run the Flask/Python file on PythonAnywhere but I'm getting an error.

What I have:

import MySQLdb

# I have the actual credentials, just changed for this forum post
username = 'username'
password = 'pass'
hostname = ''
db = 'username$zipcodes'

conn = MySQLdb.connect(host=hostname, user=username, passwd=password, db=db)
cursor = conn.cursor()

#cursor.execute('SELECT * from ')
#row = cursor.fetchone()




MySQLdb._exceptions.OperationalError: (2002, "Can't connect to MySQL server on '' (10060)")

I've referred to this and other links ( but I don't know where I'm going wrong here. If MySQLdb isn't viable, then what's the simplest way to interact with the MySQL database?


If you want to connect to MySQL on PythonAnywhere from your local machine, you need to use the SSH tunnel. See


Hi, thanks for the link, I tried it and I get this error:

File "C:/Users/User/Desktop/paymentWebsite/", line 66, in <module> conn = db.connectDB()
File "C:/Users/User/Desktop/paymentWebsite/", line 44, in connectDB database=self.db,
mysql.connector.errors.InterfaceError: 2013: Lost connection to MySQL server during query

My code:

import mysql.connector
import sshtunnel

# the def functions are indented
class connectDatabase():

def __init__(self):
    self.ssh_hostname = ''

def connectDB(self):
    sshtunnel.SSH_TIMEOUT = 5.0
    sshtunnel.TUNNEL_TIMEOUT = 5.0

    with sshtunnel.SSHTunnelForwarder(
            ssh_username=self.username, ssh_password=self.password,
            remote_bind_address=(self.hostname, 3306)
    ) as tunnel:
        connection = mysql.connector.connect(
            user=self.username, password=self.DB_password,
            host='', port=tunnel.local_bind_port,

        # Do stuff

# outside the class
db = connectDatabase()
conn = db.connectDB()

"here" doesn't get printed.
I'm just trying to establish connection to the MySQL database (named zipcodes) and I haven't executed any SQL query yet. I looked up this error but it seems like other people experienced this when trying to execute queries/getting timed out or something.

Local machine on Windows 10. Any advice for this?


You have a free account. Free accounts cannot use SSH to connect in to PythonAnywhere.

oh ok thanks, I'll try it again on my other account that's paid ($5).

It will work there.