Eb1993
Eb1993

Reputation: 13

python database application try except block

this is a login function in an application interacting with a database in postresql. I'm new to python and currently both print statements in the except blocks are being executed. The error is in: cur.execute(mtype, (member_id, )) Any ideas about why much appreciated.

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

Upvotes: 0

Views: 1336

Answers (2)

pbuck
pbuck

Reputation: 4551

You have multiple %s in your initial mtype assignment, yet your execute provides a tuple with only a single parameter. This will fail. This can be fixed by providing the correct number of parameters in execute:

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

Of course, there may be other errors in the code: one shouldn't catch Exceptions blindly unless, really, you don't care what the error is.

Upvotes: 1

Ritwik G
Ritwik G

Reputation: 416

I don't have enough points to make a comment. So posting here. Just saying which line produces error doesn't give a lot of insight into the problem. My advice is either you print what is the error or in case you don't know how to do that, remove the first try catch and see what is the error produced. If you post that people could help you resolve it.

Upvotes: 0

Related Questions