Query database with SQLAlchemy

3

I am trying to apply a query to a table, using the ORM sqlalchemy in a database already created with mysql, with the following code:

eng = create_engine("mysql+mysqldb://host='localhost', user='root', passwd='...',port='3307', database='Nomina_jul15'")

Session = sessionmaker (bind=eng)
session = Session()  

def Ver():
    print("Estas en la Opcion Ver Empleados ")
    print("")
    print("idEmpleados \t numdocEmp  \t nombreEmp \t salbasicEmp \t fechaingEmp \t nombre_eps \t nombre_afp \t fechanacEmp \t sexoEmp")
    print("============================================================================================================================")
    for Empleados in session:

        empleados = session.query(Empleados).get(Empleados)
        print(str(empleados))

    session.close()
    print('')

And I only get the header of the report:

Estas en la Opcion Ver Empleados 

idEmpleados      numdocEmp       nombreEmp   salbasicEmp     fechaingEmp     nombre_eps      nombre_afp      fechanacEmp     sexoEmp
============================================================================================================================

I do not know if it's because I did not do the creation of the database using SQLAlchemy.

    
asked by Jsierra2017 08.08.2017 в 01:00
source

1 answer

2

The sessions serve to establish the connection to the database, you are trying to iterate the session when what you should iterate is a query. You create this query using the session you have already defined:

def Ver():
    print("Estas en la Opcion Ver Empleados ")
    print("")
    print("idEmpleados \t numdocEmp  \t nombreEmp \t salbasicEmp \t fechaingEmp \t nombre_eps \t nombre_afp \t fechanacEmp \t sexoEmp")
    print("============================================================================================================================")
    for empleado in session.query(Empleados):
        print(empleado.id) # Imprime en pantalla los campos que necesites

    session.close()
    print('')

With this you are iterating every record in the table without any specific order. If, for example, you would like to order them by name you can use:

for empleado in session.query(Empleados).order_by(Empleados.nombre):
    print(empleado.id) 
    
answered by 08.08.2017 / 01:21
source