python psycopg2 如何在提交许多查询时忽略一些内部错误

How can python psycopg2 ignore some internal error when commit many queries

我在使用 python psycopg2 时遇到了一些问题,提交了一些查询,下面是我的代码:

db = psycopg2.connect(database="**", user="**", password="**", host="**", port="**")
cursor = db.cursor()
cursor.execute("***") # actually I have many cursor.execute()
db.commit()

我的问题是当提交这么多查询时,如果其中一些出现错误,整个提交程序就会死掉,我怎么能忽略这些错误并提交其余的查询?

我尝试做一些事情:

db = psycopg2.connect(database="**", user="**", password="**", host="**", port="**")
cursor = db.cursor()
cursor.execute("***") # many cursor.execute()
for i in range(3):
    try:
        db.commit()
        break
    except Exception, e:
        db.rollback()
        log.write(traceback.format_exc() + "\n\n sql error: " + e.pgerror)
        time.sleep(1.5)

但是好像不行,谁能帮帮我?

你不会做下面的事情吗?

db = psycopg2.connect(database="**", user="**", password="**", host="**", port="**")
cursor = db.cursor()
for i in range(3):
    try:
        cursor.execute("***")
    except Exception, e:
        db.rollback()
    else:
        db.commit()

您可以不用交易,使用 db.autocommit = True。或者,您可以使用 SAVEPOINTROLLBACK TO SAVEPOINT sql 语句。