Duplicate entry '0' for key 'PRIMARY'

20 views
Skip to first unread message

Martin Parrag

unread,
Sep 21, 2023, 10:53:14 AM9/21/23
to sqlalchemy
Hi Guys!

I have ORMs with autoincrement primary keys, and I'd like to achive a multiple insert with sqlalchemy.
I'm making a lot of objects and adding them to the session, and after I'm done, I'd like to make session.commit() but then I get this error: (MySQLdb.IntegrityError) (1062, "Duplicate entry '0' for key 'PRIMARY'").

Some example code.

class Base(DeclarativeBase):
    pass

class Partner(Base):
    __tablename__ = 'partner'

    id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
    name: Mapped[Optional[str]] = mapped_column(String(255, collation='utf8mb4_unicode_ci'), nullable=True, default=None)
    address: Mapped[Optional[str]] = mapped_column(String(255, collation='utf8mb4_unicode_ci'), nullable=True, default=None)

class ImportHandler:

def __init__(self, db_name: str):
plain_engine = create_engine(os.getenv('db_connection') + db_name + '?charset=utf8mb4', echo='debug')
self.session = Session(plain_engine)

def import(self):

for i in range(10):

                      partner = Partner()
                      partner.name = "Some"
                      partner.address = "Test"
                      self.session.add(partner)

            self.session.commit()

Can anybody explain that how can I solve this?
Thank you very much!

Martin Parrag

unread,
Sep 21, 2023, 11:06:31 AM9/21/23
to sqlalchemy
Hi All!

Crisis reverted, turned out my database column didn't have the autoincerement flag.
Sorry for the topic.
Reply all
Reply to author
Forward
0 new messages