【发布时间】:2021-05-22 03:34:39
【问题描述】:
所以我在这里按照给定的代码:
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()
既然我已经连接到数据库,我基本上只是想做一些非常简单的事情。我只想打印出表格的内容。当我尝试这样做时,我的代码看起来像(我填写了所需的数据,它不再是模板):
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()
我的代码在“do stuff”注释下没有我的代码编译得很好。当我添加该代码时,我得到了错误:
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.
任何关于我做错了什么的帮助或另一种方法都会很棒。谢谢!
【问题讨论】:
-
您是否在检查是否能够使用您在隧道中使用的详细信息仅打开与 PythonAnywhere 帐户的 ssh 连接?
-
我相信我能够连接。我现在只想使用 mysql.connector 库运行一个简单的函数。我只想在我的 python 脚本中的表格中显示数据,但我不确定如何。
标签: python mysql pythonanywhere