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:
print("Starting database connection test...")
import mysql.connector
import os
from dotenv import load_dotenv
load_dotenv(r"C:\Users\Skip\Documents\personal-projects-github\hairsalon-flask-web-app\.env")
print("Environment variables loaded.")
db_config = {
"host": os.getenv("DB_HOST", "localhost"),
"user": os.getenv("DB_USER", "root"),
"password": os.getenv("DB_PASSWORD", ""),
"database": os.getenv("DB_NAME", "salon"),
"port": int(os.getenv("DB_PORT", "3306")),
"auth_plugin": "mysql_native_password",
}
print("Attempting to connect to the database...")
print("Database configuration:", db_config)
try:
print("Connecting to MySQL...")
conn = mysql.connector.connect(**db_config)
print("Connected to MySQL database!")
conn.close()
except Exception as e:
print("Error connecting to MySQL:", e)
Edit: Here's a sample output
C:\Users\Skip\Documents\personal-projects-github\hairsalon-flask-web-app>python tests\sql-connector_test.py
Starting database connection test...
Environment variables loaded.
Attempting to connect to the database...
Database configuration: {'host': 'localhost', 'user': 'root', 'password': '####', 'database': 'salon', 'port': 3306, 'auth_plugin': 'mysql_native_password'}
Connecting to MySQL...
C:\Users\Skip\Documents\personal-projects-github\hairsalon-flask-web-app>
mysql -u root -p salon) ?