Flask-sqalchemy and oracle database id not autoincrement

半城伤御伤魂 提交于 2019-12-20 04:58:26

问题


I want to make a new table in my database (Oracle 11g but the Express Edition for Ubuntu 16.04) using Python and Flask framework with the SQLAlchemy module. The first field of the table it's and ID, is an Integer field and I want it to autoincrement, but Oracle database don't support the autoincrement. I have a form to add a new comment, but when I try to add a new record it reports a error:

sqlalchemy.exc.IntegrityError: (cx_Oracle.IntegrityError) ORA-01400: cannot insert NULL into ("WIKTOR"."TBL_COMENTARIOS"."ID") [SQL: 'INSERT INTO tbl_comentarios (usuario, comentario, fecha) VALUES (:usuario, :comentario, :fecha) RETURNING tbl_comentarios.id INTO :ret_0'] [parameters: {'usuario': 'wiktor', 'comentario': 'hola', 'fecha': datetime.datetime(2017, 5, 24, 11, 23, 45, 39450), 'ret_0': }]

Basically it says that the ID cannot be null, that happens because there's no field in the form to add it so it sends the id empty and then the autoincrement of the database model don't work. Here's the code:

db = SQLAlchemy()

class Comentarios(db.Model):
    __tablename__ = 'tbl_comentarios'
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    usuario = db.Column(db.String(50))
    comentario = db.Column(db.Text())
    fecha = db.Column(db.DateTime, default = datetime.datetime.now)

def __init__(self, usuario, comentario):
    self.usuario = usuario
    self.comentario = comentario

I also tried:

id = db.Column(db.Integer, primary_key=True)

That code did work in SQL Database but neither works in Oracle Database.

Sorry for my english, I hope someone can help me... Thanks!


回答1:


You can find here the SQLAlchemy documentation that discusses this. Oracle has no auto increment feature and relies on sequence to mimic the behavior.

So, your id column should look like this:

id_seq = Sequence('id_seq')
id = db.Column(db.Integer, id_seq,
        server_default=id_seq.next_value(), primary_key=True)


来源:https://stackoverflow.com/questions/44154458/flask-sqalchemy-and-oracle-database-id-not-autoincrement

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!