There are several ways to update a table, using sqlalchemy.update
you can do the following:
from sqlalchemy import update
if opcionMenu == "A":
print("Has pulsado la Opcion Modificar Numero de Documento Empleado")
numdocEmp = int(input("Digite el idCodigo del Empleado a Modificar :"))
nuevonumdocEmp = int(input("Digite el Nuevo numero de Docuemnto del Empleado a Modificar :"))
stmt = update(Empleado)\
.where(Empleado.numdocEmp == numdocEmp)\
.values(numdocEmp = nuevonumdocEmp)
session.execute(stmt)
session.commit()
Where Empleado
is your mapped base class, whose instances form the rows of your empleados
table.
Another very simple option if you use the declarative system is to obtain the row or rows with query
and then simply modify the attributes you want:
-
Loading the objects:
if opcionMenu == "A":
print("Has pulsado la Opcion Modificar Numero de Documento Empleado")
numdocEmp = int(input("Digite el idCodigo del Empleado a Modificar :"))
nuevonumdocEmp = int(input("Digite el Nuevo numero de Docuemnto del Empleado a Modificar :"))
rows = session.query(Empleado).filter(Empleado.numdocEmp == numdocEmp)
if rows:
for row in rows:
row.numdocEmp = nuevonumdocEmp
session.commit()
else:
print("Número no encontrado")
In this case it is assumed that only one row with that value will exist, however you can iterate over the whole result instead of using first()
if this is not the case.
-
Directly on the database (using the method update
of query
):
if opcionMenu == "A":
print("Has pulsado la Opcion Modificar Numero de Documento Empleado")
numdocEmp = int(input("Digite el idCodigo del Empleado a Modificar :"))
nuevonumdocEmp = int(input("Digite el Nuevo numero de Docuemnto del Empleado a Modificar :"))
session.query(Empleado)\
.filter(Empleado.numdocEmp==numdocEmp)\
.update({"numdocEmp": nuevonumdocEmp})
session.commit()
As a point, when debugging this type of "silent" problems, it is often helpful to specify the parameter echo
as True
when declaring the engine of the database:
engine = create_engine('sqlite:///myexampledb.db', echo=True)
This allows us to see by console in quite detail all the interactions between SQLAlchemy and the database itself.