I'm doing a Python's function with SQLAlchemy, i'm looking for a easy method of "select". The input variables are the name of the table and kwargs that they will be used to the condition "where".
For example, the query code would be like:
select * from Pruebas where Codigo='123' and Nombre='Leche'
And the Python's function would be like:
my_stmt('Pruebas',Codigo='123',Nombre='leche')
The structure table is:
**Pruebas**
Codigo---Nombre ---Valor
'123' ---'Leche'---'5000'
The principal code is here:
import sqlalchemy
def my_stmt(TableName,**kwargs):
table = sqlalchemy.Table(TableName, metadata, autoload=True, schema=esquema)
stmt = lambda_stmt(lambda: select(table))
for key, value in kwargs.items():
col = column(key)
stmt = stmt.add_criteria(lambda s: s.where(col == value))
#stmt += lambda s: s.where(col == value) ##On this way i obtain the same answer
return stmt
The intake of the funtion would be like:
x=my_stmt('pruebas',codigo='123',nombre='leche')
with engine.connect() as connection:
results = connection.execute(x).fetchall()
print(results)
The log console show me the next information:
SELECT dbo.pruebas.codigo, dbo.pruebas.nombre, dbo.pruebas.valor
FROM dbo.pruebas
WHERE codigo = ? AND nombre = ?
('leche', 'leche')
That's the problem, 'leche' for both conditions and i obtain a wrong answer. The print show me:
[]
The right answer that i looking for is:
[('123', 'leche', '5000')]
And the log should show me:
('123', 'leche')
I will appreciate any recommendation and if you know one more easy way to make what i need, i will be very thank you. One more thing, sorry for my English~