You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python代码中‘Connection refused’报错含义及数据库连接问题咨询

关于Python中"Connection refused"数据库连接报错的解析与解决

Hey there! Let's break down what that Connection refused error means and walk through how to fix it for your peewee-MySQL setup.

First, let's get the basics straight: this error tells you that your Python program tried to establish a connection to the MySQL server at localhost:3306, but the server didn't accept the connection request at all. It's not a wrong password or missing database issue—something is blocking the connection entirely, or the server isn't even running.

Here are the most common fixes tailored to your code and scenario:

1. Make sure your MySQL server is actually running

This is the most frequent culprit.

  • On Windows: Open the Services app (search for "Services"), find the MySQL service, and check if it's set to "Running". If not, right-click and start it.
  • On Linux/macOS: Run this command in your terminal to check status:
    sudo systemctl status mysql
    
    If it's inactive, start it with:
    sudo systemctl start mysql
    
    For macOS users who installed MySQL via Homebrew, use:
    brew services start mysql
    

2. Verify your connection port is correct

Your code uses the default MySQL port 3306, but if you've modified your MySQL configuration to use a different port, this will fail. Check your MySQL config file (usually my.cnf on Linux/macOS, my.ini on Windows) for the port setting, and update the port parameter in your MySQLDatabase call if needed.

3. Force a TCP/IP connection instead of using Unix socket

Sometimes localhost on Unix-like systems resolves to a Unix socket instead of a TCP/IP connection, which can cause this error even if the server is running. Try changing your host parameter from "localhost" to "127.0.0.1"—this forces the connection to use TCP/IP, which matches how peewee expects to connect by default.

4. Check if your root user is allowed to connect via TCP/IP

Your MySQL root user might be restricted to only connect via Unix socket (not TCP/IP). To fix this:

  1. First, log into MySQL using the socket connection (run mysql -u root in your terminal—this should work if the server is running).
  2. Run these SQL commands to grant TCP/IP access to the root user for your new database:
    GRANT ALL PRIVILEGES ON new.* TO 'root'@'127.0.0.1' IDENTIFIED BY '';
    FLUSH PRIVILEGES;
    
    (If you've set a password for your root user, replace the empty string with your actual password.)

5. Rule out firewall/security software interference

Local firewalls or antivirus programs might be blocking traffic on port 3306. Try temporarily disabling them to see if the connection works, then add a rule to allow MySQL and your Python program to communicate through the port if that fixes it.

6. Double-check your root password

Your code sets passwd="", but if you've configured a password for your MySQL root user, leaving this blank will cause connection issues. Update the passwd parameter with your actual root password if you have one.

Modified Example Code

Here's a tweaked version of your code with some best practices (like error handling and explicit TCP/IP connection):

import peewee

# Use 127.0.0.1 to force TCP/IP connection
myDB = peewee.MySQLDatabase(
    "new", 
    host="127.0.0.1",
    port=3306, 
    user="root", 
    passwd="your_root_password_here"  # Replace with actual password if set
)

class MySQLModel(peewee.Model):
    class Meta:
        database = myDB

class NewPost(MySQLModel):
    id = peewee.PrimaryKeyField()
    width = peewee.CharField()
    height = peewee.CharField()
    pixel = peewee.CharField()
    image = peewee.CharField()

try:
    myDB.connect()
    if __name__ == '__main__':
        # Create table if it doesn't exist (safe=True avoids errors if table exists)
        myDB.create_tables([NewPost], safe=True)
        print("Connection successful, table created (or already exists)!")
except peewee.OperationalError as e:
    print(f"Connection failed: {e}")
finally:
    # Make sure to close the connection when done
    if not myDB.is_closed():
        myDB.close()

内容的提问来源于stack exchange,提问作者Elin_Ashena

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 07:33:20