pythonmariadbpymysqltry-exceptdbconnection

Handling exception when there are multiple sql queries to be fired


I am fetching data from database using four select queries. The data is in such a way that there are cases when the input to select query may be empty. In that case it is okay for that particular select statement to not work. In short, what I want is that the four select statements should fire and whichever statements work should work irrespective of other query getting failed.

try:
    cur.execute("select IP_ADD,VENDOR,DVC_ROLE,CIRCLE,SSA,REGION from DVC_SUMMARY_DATA where IP_ADD in (%s);" % ip_i)

except Exception as e:
    print("error while fetching details " + str(e))

result_i = cur.fetchall()

try:
    cur.execute("select IP_ADD,VENDOR,DVC_ROLE,CIRCLE,SSA,REGION from DVC_SUMMARY_DATA where IP_ADD in (%s);" % ip_n)

except Exception as e:
    print("error while fetching details " + str(e))

result_n = cur.fetchall()

try:
    cur.execute("select IP_ADD,VENDOR,DVC_ROLE,CIRCLE,SSA,REGION from DVC_SUMMARY_DATA where IP_ADD in (%s);" % ip_c)

except Exception as e:
    print("error while fetching details " + str(e))

result_c = cur.fetchall()

try:
    cur.execute("select IP_ADD,VENDOR,DVC_ROLE,CIRCLE,SSA,REGION from DVC_SUMMARY_DATA where IP_ADD in (%s);" % ip_b)

except Exception as e:
    print("error while fetching details " + str(e))

result_b = cur.fetchall()

Solution

  • yes just put it in a for loop.

    ip_list = [ip_i, ip_n, ip_c, ip_b]
    result_list = []
    
    for ip in ip_list:
        try:
            cur.execute("select IP_ADD,VENDOR,DVC_ROLE,CIRCLE,SSA,REGION from DVC_SUMMARY_DATA where IP_ADD in (%s);" % ip)
    
        except Exception as e:
            print("error while fetching details " + str(e))        
    
        result_list.append(cur.fetchall())
    

    I am guessing that cur.fetchall() does not generate an error, if it does or you don't want it to run then you can put it inside the try one.

    So I would change it to this to keep track of which generated errors;

    ip_list = [ip_i, ip_n, ip_c, ip_b]
    result_list = []
    
    for ip in ip_list:
        try:
            cur.execute("select IP_ADD,VENDOR,DVC_ROLE,CIRCLE,SSA,REGION from DVC_SUMMARY_DATA where IP_ADD in (%s);" % ip)
            result_list.append(cur.fetchall())
    
        except Exception as e:
            print("error while fetching details " + str(e))  
            result_list.append("ERROR")