繁体   English   中英

在异常中引发验证错误时如何继续循环并记录错误?

[英]How to continue loop and log error when validation error is raised in exception?

我对 python 很陌生,但我创建了一个小脚本来在 postgres 中插入行,以及一个存储股票价格的表。 该表对日期和股票代码具有唯一约束,以确保每天每个股票代码仅插入一个价格。 我希望脚本跳过插入并继续执行其余操作,但我不知道如何在触发异常块时使循环继续。

Python脚本如下:

def createConnection(db="db", user="john", password='doe', host='host', port=5432):
    conn = psycopg2.connect(
        database=db, user=user, password=password, host=host, port=port)
    return conn


def insertNewPrices(df):
    conn = createConnection()
    cur = conn.cursor()
    for row in df.head().itertuples(index=False):
        try:
            print(row)
            cur.execute(
                "INSERT INTO daily_price (price_date, ticker, close_price) VALUES (%s, %s, 
%s)", row)
        except psycopg2.IntegrityError as e:
            print("something went wrong")
            print(e)
            continue
    conn.commit()
    conn.close()

引发的错误:

psycopg2.errors.UniqueViolation: duplicate key value violates unique constraint "daily_price_ticker_price_date_key"
DETAIL:  Key (ticker, price_date)=(EQUINOR, 1990-02-28) already exists.

你在 try 语句之外有 insert 语句。 你能从外面取下插件吗,你应该没问题。

    for row in df.head().itertuples(index=False):
        #cur.execute(
        #    "INSERT INTO daily_price (price_date, ticker, close_price) VALUES (%s, %s, %s)", 
row)
        try:
            print(row)
            cur.execute(
                "INSERT INTO daily_price (price_date, ticker, close_price) VALUES (%s, %s, 
%s)", row)
        except psycopg2.IntegrityError, psycopg2.errors.UniqueViolation) as e:
            print("something went wrong")
            print(e)

此外,您不需要在 except 语句的末尾继续作为它的最后一行。

除了检查特定错误之外,您还可以使用以下命令捕获所有错误和警告:

except (psycopg2.Error, psycopg2.Warning) as e:

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM