【问题标题】:how handle a variable if it's returning none [duplicate]如果变量没有返回,如何处理它[重复]
【发布时间】:2016-09-22 17:30:20
【问题描述】:

您好,我有以下函数可以从我的模板中获取 sql。变量行正在获取用户输入的查询。如果用户输入了一个无效的 sql,我会得到一个错误 UnboundLocalError: local variable 'row' referenced before assignment (因为没有行,因为 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

【问题讨论】:

  • 那么,当 SQL 无效时,您希望发生什么?

标签: python mysql django exception fetchall


【解决方案1】:

在返回之前声明变量,例如:

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

【讨论】:

    【解决方案2】:
    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"
    

    【讨论】:

    • 返回一个字符串而不是一个行集是一个非常糟糕的建议......
    【解决方案3】:

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

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

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

    【讨论】:

      猜你喜欢
      • 2017-08-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-01
      • 2012-06-22
      • 1970-01-01
      • 2022-01-23
      相关资源
      最近更新 更多