how handle a variable if it's returning none

Question:

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
Asked By: vellattukudy

||

Answers:

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
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"
Answered By: user5698387

I would change the code slightly to see if cursor.execute() has returned anything before doing a cursor.fetchall().

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

You can handle the error as appropriate to your application.

Answered By: MichaelJohn