Forums

Can't access MySQL db

Hello,

To make SSH connection on Windows 10 and Rasbian devices I got at home I have run the following command:

ssh -L 3306:mselvenis.mysql.pythonanywhere-services.com:3306 mselvenis@ssh.pythonanywhere.com

I had my password requested and seems that a connection has been successfully established since no error has come and I can fetch a console on my PythonAnywhere dashboard. But still I can't access my database using the following Python script:

import mysql.connector

mydb = mysql.connector.connect(
    host="mselvenis.mysql.pythonanywhere-services.com",
    user="mselvenis",
    passwd="passs",
    database="mselvenis$scraper"
)
print('connected')
mycursor = mydb.cursor()

mycursor.execute("SHOW TABLES")

for x in mycursor:
  print(x)

Running the very same code on website console print out tables with no problems.

Any advice, or I'm missing on something?

Once you have the SSH tunnel running, it acts as a server on your local machine that forwards stuff over the SSH connection to the MySQL server on PythonAnywhere. That means that to connect to it, the host parameter should be set to localhost instead of to the hostname that you would use when running code inside PythonAnywhere -- that is:

mydb = mysql.connector.connect(
    host="localhost",
    user="mselvenis",
    passwd="passs",
    database="mselvenis$scraper"
)

It worked. Thank you.

Excellent, thanks for confirming!