.cursor() 给出 MySQL 不可用

.cursor() gives MySQL not available

我正在尝试从 Python 连接到现有的 MySQL 数据库并创建一个 table。以下是代码:

from getpass import getpass
from mysql.connector import connect, Error

def connect_db():
    try:
        with connect(
                host="localhost",
                user=input("Enter username: "),
                password=getpass("Enter password: "),
                database="online_movie_rating",
            ) as connection :
            return connection
    except Error as e:
        print(e)

create_ratings_table_query = """
CREATE TABLE ratings (
    movie_id INT,
    reviewer_id INT,
    rating DECIMAL(2,1),
    FOREIGN KEY(movie_id) REFERENCES movies(id),
    FOREIGN KEY(reviewer_id) REFERENCES reviewers(id),
    PRIMARY KEY(movie_id, reviewer_id)
);
"""
cnx = connect_db()

print(cnx)

cursor = cnx.cursor()
cursor.execute(create_ratings_table_query)
cnx.commit()

当我评论最后 3 行时,我能够打印连接对象。但是,当我取消注释并尝试 运行 时,出现以下错误:

cursor = cnx.cursor()
mysql.connector.errors.OperationalError: MySQL Connection not available.

我在 Fedora 33 OS、Python 3.8.5 conda 环境中使用 VS Code 作为 IDE。已经 pip 安装了 mysql-connector-python.

有人可以帮忙吗?已经做了很多谷歌搜索,但找不到明确的答案。

提前致谢

您有:

def connect_db():
    try:
        with connect(
                host="localhost",
                user=input("Enter username: "),
                password=getpass("Enter password: "),
                database="online_movie_rating",
            ) as connection :
            return connection
    except Error as e:
        print(e)

但是一旦您的 return connection 执行,with connect(...) as connection: 块就会终止并且连接会关闭。因此,如果连接成功,您将 return 关闭连接。您需要:

def connect_db():
    try:
        connection = connect(
                host="localhost",
                user=input("Enter username: "),
                password=getpass("Enter password: "),
                database="online_movie_rating",
            )
        return connection
    except Error as e:
        print(e)

调用者可以使用 cnx.close() 明确关闭连接,或者当没有更多对此连接的引用时,例如当 cnx 超出范围时,连接将自动关闭。

此外,如果连接出错,函数connect_db将return None。所以也许调用者应该检查这种可能性。

然而,您得到的实际异常解释为:

This exception is raised for errors which are related to MySQL's operations. For example: too many connections; a host name could not be resolved; bad handshake; server is shutting down, communication errors.

您需要检查您的连接参数。但很明显,您必须对上述来源进行更改。