【问题标题】:PythonAnywhere Mysql Database From PythonPythonAnywhere 来自 Python 的 Mysql 数据库
【发布时间】: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


【解决方案1】:

你需要给它更多的参数,比如端口号和数据库名。 如果您安装和配置了 mysql,并且需要在代码本身上配置它,则此代码是相关的。 例子: 端口=3306 database="你在mysql上配置的数据库名。 欲了解更多信息,请访问此网站 https://dev.mysql.com/doc/connector-python/en/connector-python-example-connecting.html

【讨论】:

  • 我这样做了,只是我没有输入自己的输入,所以我的数据不在互联网上。
  • 我会考虑让 mysql 监听任何连接以进行测试。例如听 0.0.0.0/0
  • 尝试点击此链接。 stackoverflow.com/questions/27537892/…我会写下更多信息,但是我有一个小孩在写下它时对我大喊大叫
猜你喜欢
  • 1970-01-01
  • 2012-06-11
  • 1970-01-01
  • 2015-05-31
  • 2015-05-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多