0

I have created a database main_data with a table users. When I try to add a new record to the table, I get the following error:

sqlalchemy.exc.OperationalError: (pymysql.err.OperationalError) (1364, "Field 'id' doesn't have a default value")

There are no normal guides and solutions to the problem on the Internet. Source code:

from sqlalchemy import create_engine
from sqlalchemy_utils import database_exists
from sqlalchemy import Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker

DATABASE_NAME = "main_data"
engine = create_engine(f"mysql+pymysql://root:toor/{DATABASE_NAME}")
Base = declarative_base()


class Users(Base):
    __tablename__ = "users"

    id = Column(Integer, primary_key=True)
    user_id = Column(Integer)
    username = Column(String)
    status = Column(String)
    name = Column(String)
    location_city = Column(String)
    location_address = Column(String)
    contacts = Column(String)
    announcements = Column(String)
    balance = Column(Integer)


Session = sessionmaker(bind=engine)
session = Session()


def add_user(user_id, username, status, name, location_city, location_address, contacts, announcements, balance):
    user = Users(user_id=user_id, username=username, status=status, name=name, location_city=location_city,
                 location_address=location_address, contacts=contacts, announcements=announcements, balance=balance)
    session.add(user)
    session.commit()

Raleyph
  • 43
  • 1
  • 5
  • The `add_user()` function is _defined_ but it is never _called_. There must be more code you haven't shown us. – John Gordon Nov 19 '22 at 02:53
  • 1
    @JohnGordon Genius! But I'm asking why the code is giving an error instead of not working... – Raleyph Nov 19 '22 at 03:36
  • This code does not call `add_user()`, therefore the error must be coming from some other code you haven't shown us. You're asking us about code we can't see. How are we supposed to answer? Do you suppose we have a crystal ball? – John Gordon Nov 19 '22 at 03:46
  • Just the same error here. I just call this function from somewhere else in the code and pass the values ​​there. – Raleyph Nov 19 '22 at 14:44
  • 1
    A likely cause is that the table was initially created without `AUTO_INCREMENT` being set on the column. If so, this is a duplicate of [this Q&A](https://stackoverflow.com/q/25865104/5320906). – snakecharmerb Jan 06 '23 at 14:43

0 Answers0