2016-05-25 10 views
0

こんにちは私はテンプレートから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 
+0

SQLが無効なときにはどうしますか? – ysth

答えて

0

Declarete変数復帰する前に、何かのように:cursor.executeは()cursor.fetchallを行う前に何を返した場合、私は(見て少しコードを変更します

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" 
+0

行セットの代わりに文字列を返すことは非常に悪いアドバイスです。 – Selcuk

+0

rly、なぜですか?説明する – user5698387

0

) 。

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

アプリケーションに応じてエラーを処理できます。

関連する問題