[Python] Python MySQL Connection Hangs Using mysql-connector-python

Discussão em 'Python' iniciado por Stack, Março 16, 2025.

  1. Stack

    Stack Membro Participativo

    My Python script hangs when trying to connect my Flask app to a MySQL database using mysql-connector-python. The MySQL server is running because it runs perfectly in VSCode, but I can't connect via the command line.

    What I’ve Tried:


    Verified MySQL server is running. Installed mysql-connector-python (v9.2.0). Added connect_timeout.

    I even set a timeout on the connection attempt so why does the script hang, and how can I fix it?

    Here’s the test for the connection:


    import mysql.connector
    from dotenv import load_dotenv
    import os

    load_dotenv()

    db_config = {
    "host": os.getenv("DB_HOST", "localhost"),
    "user": os.getenv("DB_USER", "root"),
    "password": os.getenv("DB_PASSWORD", ""),
    "database": os.getenv("DB_NAME", "...."),
    "port": int(os.getenv("DB_PORT", "...")),
    "auth_plugin": "mysql_native_password",
    } # intentionally blurred out details for privacy

    try:
    print("Connecting to MySQL...")
    conn = mysql.connector.connect(**db_config, connect_timeout=5)
    print("Connected to MySQL database!")
    conn.close()
    except mysql.connector.Error as e:
    print("MySQL Error:", e)
    except Exception as e:
    print("General Error:", e)

    Continue reading...

Compartilhe esta Página