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

Python UDP服务端接收数据后无法写入MySQL:数据库连接异常求助

Hey there! Let's figure out why your MySQL connection isn't working—you're right that the issue lies in the mysql.connector.connect() section since "running" never prints. Here are the key problems and fixes:

1. Port Conflict & Incorrect MySQL Port

You set port="8888" for MySQL, but the default MySQL port is 3306. To make things worse, your UDP socket also binds to port 8888 later in the code—even if MySQL was configured to use 8888, the socket would already be occupying that port, making the connection impossible.

Fix: Change the MySQL port to 3306 (unless you explicitly modified your MySQL settings to use a different port, double-check your MySQL config first).

2. Missing Error Handling

Your code doesn't catch any exceptions when connecting to MySQL. If there's a failure (wrong credentials, non-existent database, network issue), the script will crash silently without telling you what went wrong.

Fix: Wrap the connection code in a try-except block to capture and print error details—this will help you pinpoint exactly what's failing.

3. Minor Issue with Database Insert

When you define val = (data), this isn't actually a tuple—it's just the variable data wrapped in parentheses. MySQL's execute() expects a tuple for parameterized queries, so you need to add a trailing comma to make it a valid tuple: val = (data,).


Here's the revised code with all these fixes applied:

import mysql.connector
from mysql.connector import Error
import socket

print("checking")
try:
    mydb = mysql.connector.connect(
        host="127.0.0.1",
        port="3306",  # Updated to default MySQL port
        user="root",
        password="000000",
        auth_plugin="mysql_native_password",
        database="final"
    )
    print("running")
    
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    sock.bind(("127.0.0.1", 8888))  # This port is now only used by the UDP service
    
    while True:
        print('\nwaiting to receive message')
        data, addr = sock.recvfrom(1024)
        data = data.decode().upper()
        sock.sendto(data.encode(), addr)
        print('receive {} bytes from {}.'.format(len(data), addr))
        print(data)
        
        mycursor = mydb.cursor()
        sql = "INSERT INTO final (name) VALUES (%s)"
        val = (data,)  # Trailing comma to create a valid tuple
        mycursor.execute(sql, val)
        mydb.commit()
        print(mycursor.rowcount, "record inserted.")
        
except Error as e:
    print(f"Error connecting to MySQL: {e}")
finally:
    # Clean up connections properly
    if 'mydb' in locals() and mydb.is_connected():
        mycursor.close()
        mydb.close()
        print("MySQL connection closed")
    if 'sock' in locals():
        sock.close()

After making these changes, run the script again. If there's still an issue, the error message from the except block will tell you exactly what's wrong—like if the final database doesn't exist, or your root password is incorrect.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 10:47:50