Reputation: 43
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!
Upvotes: 4
Views: 2456
Reputation: 144
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)
Upvotes: 10