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

Python CGI框架从MySQL取数报错:NoneType不可迭代求解决

Hey there, that error means the result variable you're trying to loop over is None—so your code is trying to iterate over nothing. Let's break down why this might be happening and how to fix it step by step.

Common Causes & Fixes

1. You used fetchone() instead of fetchall()

If you're using cursor.fetchone() to retrieve results, it returns None when there are no matching rows. This will break your loop because None isn't iterable.

Instead, use cursor.fetchall()—it returns an empty list (which is iterable) when no rows exist:

# Replace this:
result = cursor.fetchone()

# With this:
result = cursor.fetchall()

If you specifically need a single row, add a check before processing:

def displaytest(result):
    if result is None:
        print("<p>No matching records found.</p>")
        return
    # Process the single row here

2. Your query failed silently (no error handling)

A syntax error in your SQL, invalid database credentials, or a missing table can cause the query to fail. If you don't catch these errors, your code might skip assigning result entirely, leaving it as None. Add error handling around your database operations:

import MySQLdb
from MySQLdb import OperationalError, ProgrammingError

try:
    # Connect to your database
    db = MySQLdb.connect(host="localhost", user="your_username", passwd="your_password", db="your_db")
    cursor = db.cursor()
    
    # Use parameterized queries to avoid SQL injection!
    query = "SELECT * FROM your_table WHERE search_column = %s"
    cursor.execute(query, (user_input,))  # Pass user input as a tuple
    
    result = cursor.fetchall()
except OperationalError as e:
    print(f"<p>Database connection error: {str(e)}</p>")
    result = []  # Assign empty list to prevent None
except ProgrammingError as e:
    print(f"<p>SQL query error: {str(e)}</p>")
    result = []
finally:
    if 'db' in locals():
        db.close()

displaytest(result)

3. You forgot to fetch results after executing the query

It's easy to overlook this step! After running cursor.execute(), you need to explicitly retrieve the results:

# Don't skip this line!
result = cursor.fetchall()

4. Add a safety guard in your displaytest function

Even if you fix the above, adding a check for empty or None results will prevent this error from recurring:

def displaytest(result):
    # Handle empty or None results
    if not result:
        print("<p>No results to display.</p>")
        return
    
    # Your existing loop code
    for x in result:
        # Render each row (adjust based on your data structure)
        print(f"<div>{x[0]} - {x[1]}</div>")

Quick Security Note

Always use parameterized queries (like the example above) instead of string formatting for user input. This prevents SQL injection attacks, which are a critical security risk.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 08:16:46