0

在 Python ORM Pony中,如果我尝试插入一条记录但它已经存在,我想尝试更新记录。

当记录已经存在时,我收到以下错误: pony.orm.core.TransactionIntegrityError: Object Record[1234] cannot be stored in the database. IntegrityError: UNIQUE constraint failed: Record.id

编辑:但是,即使我尝试更新记录,似乎也会重新抛出此错误。这是我高度简化的示例代码:

#!/usr/bin/env python
# encoding: utf-8

from pony.orm import *

db = Database()

class Record(db.Entity):
    id = PrimaryKey(int)

db.bind("sqlite", "database.sqlite", create_db=True)
db.generate_mapping(create_tables=True)

records = [{"id":1234},{"id":1234}]

@db_session
def saveRecords(records):
    for r in records:
        try:
            Record(**r)
        except Exception as e:
            print("error caught")
            p = Record.get(id=r.get("id"))
            p.set(**r)

saveRecords(records)

想法?

4

1 回答 1

0

这对我有用

sql_debug(True)
records = [{"id":1233},{"id":1236}]

def saveRecords(records):
    with db_session:
        for r in records:
            try:
                print "inserting"
                print r
                Record(**r)
                commit()
            except Exception as e:
                print("error caught")
                print e 
            #p = Record.get(id=r.get("id"))
            #p.set(**r)

saveRecords(records)
于 2017-02-23T12:44:01.027 回答