杰瑞科技汇

Python MySQLdb连接10061错误怎么解决?

Of course. The "10061" error is a very common and specific issue when trying to connect to a MySQL database with Python. Let's break down exactly what it means, why it happens, and how to fix it.

Python MySQLdb连接10061错误怎么解决?-图1
(图片来源网络,侵删)

What Error 10061 Means: "Connection Refused"

In networking, Error 10061 (also known as WSAECONNREFUSED on Windows) is a clear and unambiguous message from your operating system.

It means: Your Python script successfully found the computer running the MySQL server, but the server itself actively refused the connection request.

Think of it like this: You dialed the correct phone number (the IP address and port), but the person on the other end picked up the phone and immediately hung up before you could say anything. The server is there, but it's configured to not talk to your script.

This is different from:

Python MySQLdb连接10061错误怎么解决?-图2
(图片来源网络,侵删)
  • Error 10060 (Timeout): The server isn't even answering the phone. It's either off, the network path is broken, or a firewall is blocking the attempt before it even reaches the server.
  • Error 2003 (Can't connect to MySQL server): Usually means the server is down or the IP/port is completely wrong.

The Top 5 Causes and How to Fix Them

Here are the most common reasons for the "Connection Refused" error, ordered from most to least frequent.

The MySQL Server Isn't Running (Most Common Cause)

The MySQL service might not be active on the machine you're trying to connect to.

How to Check & Fix:

  • On Linux (using systemd):

    Python MySQLdb连接10061错误怎么解决?-图3
    (图片来源网络,侵删)
    # Check the status of the MySQL service
    sudo systemctl status mysql
    # If it's not active, start it
    sudo systemctl start mysql
    # Enable it to start automatically on boot
    sudo systemctl enable mysql
  • On Windows:

    1. Press Win + R, type services.msc, and hit Enter.
    2. Scroll down and find the service named "MySQL" or "MySQL80" (the name varies by version).
    3. Check the "Status" column. If it's not Running, right-click it and select Start.
    4. Also, ensure the "Startup Type" is set to Automatic.

Firewall is Blocking the Connection

The server's firewall (or your local machine's firewall) is configured to block incoming connections on MySQL's default port (3306).

How to Check & Fix:

  • On the Server (Linux with ufw):

    # Check if the rule is already in place
    sudo ufw status
    # Allow connections on port 3306 (MySQL)
    sudo ufw allow 3306
  • On the Server (Windows Defender Firewall):

    1. Go to "Control Panel" > "System and Security" > "Windows Defender Firewall".
    2. Click on "Allow an app or feature through Windows Defender Firewall".
    3. Click "Change settings" (requires admin rights).
    4. Find "MySQL" in the list and ensure it's checked for both "Private" and "Public" networks. If it's not there, you may need to add it manually by clicking "Allow another app..." and navigating to your MySQL mysqld.exe file.
  • On Your Local Machine: If you are connecting from your own computer to a remote server, a local firewall (like Windows Defender or a third-party antivirus) could be blocking the outbound connection. This is less common but possible. Temporarily disabling your firewall for testing can help diagnose this.

Incorrect Connection Host (host parameter)

You might be trying to connect to the wrong server address. By default, MySQL is configured to only accept connections from localhost (the same machine the server is running on).

  • If your MySQL server is on the same machine as your Python script, you should use host='localhost' or host='127.0.0.1'.
  • If your MySQL server is on a different machine (a remote server), you must use the server's correct IP address or domain name (e.g., host='192.168.1.100' or host='your-server.com').

How to Fix: Double-check the host string in your Python code. Ensure it's the correct IP address or hostname for your database server.

MySQL is Configured for Localhost Only (bind-address)

Even if you've started the MySQL service, it might be explicitly configured to only listen for connections from localhost. This is done by the bind-address setting in the MySQL configuration file (my.cnf or my.ini).

How to Check & Fix:

  1. Locate the MySQL configuration file.

    • Linux: Usually /etc/mysql/my.cnf or /etc/my.cnf.
    • Windows: Usually C:\ProgramData\MySQL\MySQL Server 8.0\my.ini (the path can vary).
  2. Edit the file and find the [mysqld] section.

  3. Look for the line bind-address = 127.0.0.1 or bind-address = ::1.

    • 0.0.1: Only allows connections from localhost.
    • :1: The IPv6 equivalent of localhost.
  4. To allow connections from any IP address (for testing purposes only): Change the line to bind-address = 0.0.0.0. Warning: This is a security risk for a production server. For production, you should specify the specific IP addresses that are allowed to connect (e.g., bind-address = 192.168.1.100).

  5. Restart the MySQL service after making the change:

    # On Linux
    sudo systemctl restart mysql
    # On Windows (go back to the Services window and restart it)

MySQL User is Not Allowed to Connect from Your Host

Even if the server is running and the firewall is open, the specific user you're trying to authenticate with might be restricted. By default, users are only allowed to connect from localhost.

How to Check & Fix:

You need to log into the MySQL server directly (e.g., using the MySQL command-line client) and check the user's privileges.

  1. Log in to MySQL:

    mysql -u root -p

    (Enter your root password)

  2. Check the user's host permissions:

    -- Replace 'your_user' with the username from your Python script
    SELECT host, user FROM mysql.user WHERE user = 'your_user';

    You might see results like:

    • user | host
    • your_user | localhost
    • your_user | 0.0.1

    This means the user your_user can only connect if the request comes from the same machine.

  3. Grant remote access (use with caution!): To allow the user to connect from any IP address (for testing), run this command:

    -- Replace 'your_password' with the user's actual password
    GRANT ALL PRIVILEGES ON *.* TO 'your_user'@'%' IDENTIFIED BY 'your_password';
    -- Then, apply the changes
    FLUSH PRIVILEGES;

    Warning: The in 'your_user'@'%' is a wildcard that means "from any host". This is a major security risk. For a production environment, you should replace with the specific IP address of your application server (e.g., 'your_user'@'192.168.1.50').


Python Code Example and Checklist

Here is a typical connection script. Use this as a template and check against the points above.

import MySQLdb # Or use the more common 'mysql-connector-python' library
# --- CHECKLIST BEFORE RUNNING ---
# 1. Is the MySQL server RUNNING on '192.168.1.100'?
# 2. Is the FIREWALL on '192.168.1.100' allowing port 3306?
# 3. Is the 'bind-address' in my.cnf set to '0.0.0.0' or the correct IP?
# 4. Does the user 'myuser' have permission to connect from YOUR machine's IP?
# 5. Are the username, password, and database name correct?
try:
    # Replace with your actual connection details
    db = MySQLdb.connect(
        host="192.168.1.100",  # <-- CHECK THIS IP
        user="myuser",         # <-- CHECK THIS USER
        passwd="mypassword",   # <-- CHECK THIS PASSWORD
        db="mydatabase"        # <-- CHECK THIS DB NAME
    )
    print("Successfully connected to the database!")
    # You can now perform database operations
    cursor = db.cursor()
分享:
扫描分享到社交APP
上一篇
下一篇