【问题标题】:How to update database according to the error message I get?如何根据我收到的错误消息更新数据库?
【发布时间】:2021-12-26 19:57:03
【问题描述】:

我有一个 python 脚本和一个数据库。它们是相连的。当输入错误时,python 脚本会引发一些错误。例如,其中一项功能是对类别进行计数。如果少于 2 个类,则会引发 OneClassError 并终止程序。还有其他自定义错误,例如 OneClassError。

我的数据库表中有一个名为 error_code 的列。它应该根据我得到的具体错误进行更新。例如,如果是 OneClassError,则应该是 401;如果是 TestClassMsg,它应该是 402。 (为了便于说明,我在此编造错误名称。)

目前,我只知道如何用单个值更新该列。 我想知道如何自动化处理有 401 和 402 的过程,我不需要指定 401 或 402 - error_code 识别错误并知道它的代码。

# here is my simplified example:

def count_class_sim(inp_data):
    """
    :param inp_data:  the path of the input data

    :return: pass or fail
    """
    unique_cc, count_cc = np.unique(inp_data[inp_data != 0], return_counts=True) 
    if len(unique_cc) < 2:
        raise OneClassError()
    else: 
        raise TestClassMsg()

data1 = np.array([0,0,1,2,3,3,4,5,5,5])
count_class_sim(data1) # ---- TestClassMsg: TestingTesting

data2 = np.array([0,0,1])
count_class_sim(data2) # ---- OneClassError: Data has only 1 non-zero class - rejected.

这是我的数据库连接代码。请注意,我只知道如何为 error_code 赋予单个值。我想要一种复杂的方法来做到这一点。 谁能告诉我如何修改“set error_code =”命令?

try:
    count_class_sim(data2)
except:
    cur.execute("""update lc_2020 set error_code = 401 
                        where quad_id = '010059' """)
    conn.commit()

【问题讨论】:

    标签: python sql database postgresql error-handling


    【解决方案1】:

    由于您有自定义错误,您可以在自定义错误类本身中提及您的错误代码。

    例子:

    class OneClassError(Exception):
        code = 401
        def __init__(self):
            pass
        #remaining logic 
        
    try:
        #code that may cause Exception OneClassError
    except OneClassError as e:
        print(e.code)
    

    我希望我能理解您的问题并正确回答,如果有任何问题请在评论部分提出。

    【讨论】:

    • 嗨。感谢您的输入!我也做了一些搜索,添加代码似乎是正确的解决方案。但是我可以问你一个问题吗?所以实际上在 try 块中运行的是一个自动化脚本,整个 try-except 是另一个脚本。内层脚本中的错误码是否可以被外层脚本理解?
    • 你是说 try-except 包含一个自动生成的 try-except 块吗?如果是这种情况并且异常发生在内部 try 块中,则它必须在内部 except 块中捕获,否则如果 except 块是可编辑的,那么您可以在内部再次引发异常,除非在外部异常中捕获该错误。
    • 如果我给了你一个正确的答案。就接受吧。它将标记为已解决you can check here
    猜你喜欢
    • 2022-11-28
    • 1970-01-01
    • 2018-10-07
    • 2022-06-16
    • 2020-02-26
    • 2020-02-19
    • 2016-06-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多