Forums

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 = 'username.mysql.pythonanywhere-services.com'
db = 'username$zipcodes'


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

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

conn.close()

print(conn)
print("asdf")

Error:

MySQLdb._exceptions.OperationalError: (2002, "Can't connect to MySQL server on 'username.mysql.pythonanywhere-services.com' (10060)")

I've referred to this and other links (https://www.pythonanywhere.com/forums/topic/2477/) 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?

Thanks

If you want to connect to MySQL on PythonAnywhere from your local machine, you need to use the SSH tunnel. See https://help.pythonanywhere.com/pages/AccessingMySQLFromOutsidePythonAnywhere/

@fjl

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

File "C:/Users/User/Desktop/paymentWebsite/connectDatabase.py", line 66, in <module> conn = db.connectDB()
File "C:/Users/User/Desktop/paymentWebsite/connectDatabase.py", 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 = 'ssh.pythonanywhere.com'
            ...

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

    with sshtunnel.SSHTunnelForwarder(
            (self.ssh_hostname),
            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='127.0.0.1', port=tunnel.local_bind_port,
            database=self.db,
        )
        print("here")

        # Do stuff
        connection.close()

# 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?

Thanks

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

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

It will work there.