当要激发多个sql查询时处理异常

2024-03-29 00:03:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用四个select查询从数据库获取数据。数据的方式是,在某些情况下,select查询的输入可能为空。在这种情况下,特定的select语句不起作用是可以的。简而言之,我想要的是四个select语句应该被激发,并且不管其他查询失败,任何一个语句都应该工作。你知道吗

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()

Tags: fromipaddexecutedatasummaryselectregion
2条回答

将IP地址变量添加到列表中,然后遍历该列表。在这里,我使用traceback模块来打印整个堆栈跟踪(不仅仅是异常),并且在try块中执行fetchall,否则,如果在execute期间发生异常,您将尝试不获取任何内容。你知道吗

import traceback

ip_list = [ ip_i, ip_n, ip_c, ip_b ]

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 = cur.fetchall()

    except Exception as e:
        print(traceback.format_exc())

是的,把它放进一个for循环。你知道吗

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())

我猜是的当前fetchall()不会生成错误,如果它生成错误或您不希望它运行,则可以将它放入try one中。你知道吗

所以我会把它改成这样,以跟踪哪些产生了错误

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")      

相关问题 更多 >