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

时间:2020-10-03 18:54:25

标签: python psychopy

我对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.

1 个答案:

答案 0 :(得分:0)

在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: