So I followed the given code here:
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. yourusername.mysql.pythonanywhere-services.com', 3306)
) as tunnel:
connection = mysql.connector.connect(
user='your PythonAnywhere username', password='your PythonAnywhere database password',
host='127.0.0.1', port=tunnel.local_bind_port,
database='your database name, eg yourusername$mydatabase',
)
# Do stuff
connection.close()
I basically just want to do some very simple things now that I am connected to the database. I would like to just print out the contents of a table. When I try to do this, my code looks like (I filled in the needed data, it is not the template anymore):
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. yourusername.mysql.pythonanywhere-services.com', 3306)
) as tunnel:
connection = mysql.connector.connect(
user='your PythonAnywhere username', password='your PythonAnywhere database password',
host='127.0.0.1', port=tunnel.local_bind_port,
database='your database name, eg yourusername$mydatabase',
)
# Do stuff
stuff = connection.cursor()
stuff.execute("select * from Semesters")
for i in stuff:
print(i)
connection.close()
My code compiles fine without my code under "do stuff" comment. When I added that code, I get the error:
Traceback (most recent call last):
File "C:\Users\Bobby\python_datebase\database_connect.py", line 17, in <module>
stuff = connection.cursor()
File "E:\Python 3.9\lib\site-packages\mysql\connector\connection.py", line 809, in cursor
raise errors.OperationalError("MySQL Connection not available.")
mysql.connector.errors.OperationalError: MySQL Connection not available.
Any help on what I am doing wrong or an alternative way to do this would be awesome. Thanks!