如何处理返回的变量 none

how handle a variable if it's returning none

您好,我有以下功能可以从我的模板中获取 sql。变量行正在获取用户输入的查询。如果用户输入无效的 sql,我会得到一个错误 UnboundLocalError: local variable 'row' referenced before assignment(因为行是 none,因为 sql 是错误的)我如何有效地处理这个错误?我对 django python 有点陌生。可以帮我解决这个问题吗?提前致谢。

def DBQuery(sql):
        c = MySQLdb.connect(host=HOST,user=USER,passwd=PASS,db=DB, cursorclass=MySQLdb.cursors.DictCursor)
        cursor  = c.cursor()

        try:
            cursor.execute(sql)
            row = cursor.fetchall()
        except Exception, e:
            print "Error found!", e

        cursor.close()
        c.close()
        return row

在 return 之前声明变量,例如:

def DBQuery(sql):
    c = MySQLdb.connect(host=HOST,user=USER,passwd=PASS,db=DB, cursorclass=MySQLdb.cursors.DictCursor)
    cursor  = c.cursor()
    row = None
    try:
        cursor.execute(sql)
        row = cursor.fetchall()
    except Exception, e:
        print "Error found!", e

    cursor.close()
    c.close()
    return row
def DBQuery(sql):
        c = MySQLdb.connect(host=HOST,user=USER,passwd=PASS,db=DB, cursorclass=MySQLdb.cursors.DictCursor)
        cursor  = c.cursor()

        try:
            cursor.execute(sql)
            row = cursor.fetchall()
        except Exception, e:
            print "Error found!", e
            row="None"

        cursor.close()
        c.close()
        return row
#then if the Exception ocure, the func will ret the string "None"

我会稍微更改代码以查看 cursor.execute() 在执行 cursor.fetchall() 之前是否返回了任何内容。

rows_affected = cursor.execute(sql)
if rows_affected == 0:
    flag_an_error()
else:
    rows = ......

您可以根据您的应用程序适当地处理错误。