Problems with connecting to MySQL database in Python application

I’m encountering an issue with my Python application where it needs to save data to a MySQL database. Before I run the entire program, I wanted to test the database connection independently, but I’m having trouble.

I used the following code snippet:

import mysql.connector

database_conn = mysql.connector.connect(
    host='localhost',
    port=3306,
    user='username',
    password='password',
    database='dbname'
)

However, it just hangs and eventually times out. I tried running this from my computer and another one on the same network, but the result is the same.

Interestingly, I can connect using other command line tools with the same login details without any problems. The MySQL server appears to be up and responsive.

Has anyone faced a similar timeout issue with the MySQL connection in Python? I need some help figuring this out.

I encountered a similar issue a while back, and it turned out that the MySQL server was configured to accept connections from specific IP addresses only. Although localhost worked with command line tools, I’ve noticed that the mysql.connector sometimes has difficulty resolving ‘localhost’. Try changing ‘localhost’ to ‘127.0.0.1’ in your connection settings. Additionally, ensure that ‘skip-networking’ is disabled in your MySQL configuration, as this setting would block all TCP connections. Make sure that the ‘bind-address’ is set to ‘0.0.0.0’ or commented out altogether to allow network connections. Lastly, check if a firewall might be blocking access for Python processes.

sounds like your mysql server only accepts connections from certain hosts. check your user privileges by running SELECT user, host FROM mysql.user; to see if your username can connect from localhost. your user might exist but only work from a diff host pattern like ‘%’ or specific ips.

This timeout usually means it’s a connection pool or driver issue, not the server itself. Since your command line tools work fine, MySQL is definitely accessible. I’ve hit this exact problem when mysql-connector-python doesn’t play nice with certain MySQL versions or when SSL settings don’t match up. Try adding autocommit=True and connection_timeout=10 to your connection string - you’ll get a faster failure with a better error message. Also check if you’re running the latest mysql-connector-python version since older ones had nasty timeout bugs. Sometimes just switching to PyMySQL fixes these driver hangups while you figure out what’s really going on.