0

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
Delgan
  • 18,571
  • 11
  • 90
  • 141
vellattukudy
  • 789
  • 2
  • 11
  • 25

3 Answers3

0

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
0
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"
user5698387
  • 477
  • 3
  • 10
0

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.

MichaelJohn
  • 185
  • 3
  • 15