pythonywhere Mysql数据库来自Python

2024-05-20 02:31:39 发布

您现在位置:Python中文网/ 问答频道 /正文

因此,我在这里遵循给定的代码:

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.

任何关于我做错了什么的帮助,或者一种替代方法,都将是非常棒的。谢谢


Tags: 代码inimportyourconnectormysqltimeoutusername
1条回答
网友
1楼 · 发布于 2024-05-20 02:31:39

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

相关问题 更多 >