Forums

Can't connect to PythonAnywhere database from laptop

I'm trying to connect to my database on PythonAnywhere using the following code:

from sqlalchemy import create_engine

example_str = f'mysql+mysqldb://{user}:{pwd}@{host}/{db}'

# below code modified according to https://help.pythonanywhere.com/pages/UsingSQLAlchemywithMySQL/
engine = create_engine(example_str, pool_recycle=280, pool_pre_ping=True)
conn = engine.connect()

But I keep getting this error: OperationalError: (MySQLdb._exceptions.OperationalError) (2005, "Unknown MySQL server host '('kynnemall.mysql.pythonanywhere-services.com',)' (22)")

Also, when I run the following code in the terminal:

mysql -u kynnemall -h kynnemall.mysql.pythonanywhere-services.com -p kynnemall$default

It hangs for a very long time after I enter the password. What am I doing wrong?

I've also tried:

from sqlalchemy import create_engine

# Replace username and password with your PythonAnywhere username and password
engine = create_engine(f'mysql+mysqlconnector://{user}:{pwd}@{host}/{user}${db}',
                       pool_recycle=280, pool_pre_ping=True)

# Connect to the database
connection = engine.connect()

and I get this error:

DatabaseError: (mysql.connector.errors.DatabaseError) 2005 (HY000): Unknown MySQL server host '('kynnemall.mysql.pythonanywhere-services.com',)' (-2) (Background on this error at: https://sqlalche.me/e/14/4xp6)

I've also tried:

from sqlalchemy import create_engine
import pymysql

pymysql.install_as_MySQLdb()

# Replace username and password with your PythonAnywhere username and password
engine = create_engine(f'mysql://{user}:{pwd}@{host}/{user}${db}')

# Connect to the database
connection = engine.connect()

and get this error:

OperationalError: (pymysql.err.OperationalError) (2003, 'Can\'t connect to MySQL server on "(\'kynnemall.mysql.pythonanywhere-services.com\',)" ([Errno -2] Name or service not known)') (Background on this error at: https://sqlalche.me/e/14/e3q8)

Take a look at https://help.pythonanywhere.com/pages/AccessingMySQLFromOutsidePythonAnywhere/ but it works only for paid accounts.