pythonmysqldjangoexceptionfetchall

how handle a variable if it's returning none


Hi I have the following function to get sql from my template. variable row is fetching the query which is input by the user. If the user input an invalid sql am getting an error as UnboundLocalError: local variable 'row' referenced before assignment (Because row is none bacuse the sql is wrong) How can I handle this error effectively? Am bit new to django python. Can help me on this guys? Thanks in advance.

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

Solution

  • Declarete variable before return, something like:

    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