2017-06-03 16 views
0

這是一個在postresql中與數據庫交互的應用程序中的登錄函數。我是python的新手,目前在except塊中的兩個打印語句正在執行。 錯誤出現在:cur.execute(mtype,(member_id,))關於爲什麼讚賞的任何想法。python數據庫應用程序嘗試除塊

def check_login(member_id, password): 

    conn = database_connect() 
    if(conn is None): 
     return None 
    cur = conn.cursor() 
    try: 
     mtype = """SELECT 'athlete' FROM athlete 
         WHERE member_id=%s 
         UNION 
         SELECT 'official' FROM official 
         WHERE member_id=%s 
         UNION 
         SELECT 'staff' FROM staff 
         WHERE member_id=%s""" 
     cur.execute(mtype, (member_id,)) 
     user_type = cur.fetchone() 
    except: 
     print("Error retrieving member type") 


    try: 
     sql = """SELECT member_id, title, given_names AS first_name, family_name, country_name, place_name AS residence 
       FROM public.country JOIN public.member USING (country_code) JOIN public.place ON (accommodation = place_id) 
       WHERE member_id=%s AND pass_word=%s""" 

     cur.execute(sql, (member_id, password)) 
     user_data = cur.fetchone() 

     tuples = { 
      'member_id': user_data[0], 
      'title': user_data[1], 
      'first_name': user_data[2], 
      'family_name': user_data[3], 
      'country_name': user_data[4], 
      'residence': user_data[5], 
      'member_type': user_type[0] 
     } 
     cur.close() 
     conn.close() 
     return tuples 
    except: 
     print("Error Invalid Login") 
     cur.close() 
     conn.close() 
     return None 
+2

您正在捕獲所有異常並詢問爲什麼拋出異常而未顯示異常。 – DeepSpace

+2

不要發現異常併發布它。 –

+0

您是否想知道爲什麼例外首先被擊中?或者你想知道爲什麼例外會被打到? – Luke101

回答

1

您在初始mtype賦值中有多個%s,但您的執行只提供一個元組只有一個參數。這將失敗。這可以通過提供的參數的正確數目execute是固定的:

mtype = """SELECT... member_id=%s UNION ... member_id=%s UNION ... member_id=%s""" 
cur.execute(mtype, (member_id, member_id, member_id)) 

當然,也有可能是在代碼中其他錯誤:不應該捕捉異常盲目,除非真的,你不關心什麼錯誤是。

0

我沒有足夠的點數來發表評論。所以張貼在這裏。只要說出哪一行會產生錯誤,並不能提供有關該問題的很多信息。我的建議是要麼打印什麼是錯誤,要麼是你不知道如何去做,請刪除第一次嘗試,看看產生了什麼錯誤。如果你發佈的人可以幫助你解決它。

相關問題