考虑下表:
class Employee(Base):
__tablename__ = "t_employee"
id = Column(Integer(20), Sequence('%s_id_seq' % __tablename__), primary_key=True)
first_name = Column(String(30))
last_name = Column(String(30))
email = Column(String(50))
start_date = Column(Date, default=datetime.now)
end_date = Column(Date)
如何在sqlalchemy的原始sql中选择使用字符串而不是日期?以下适用于mysql但不适用于Oracle:
session.query(Employee).\
filter("end_date IS NULL OR end_date>='%s'" % datetime.now()).all()
最好的情况是,如果我在处理Date或DateTime列时可以使用字符串或日期(可互换)(我已经尝试过TypeDecorator无效)
请注意,问题是指原始 sql(我知道这可以使用谓词来完成)......
答案 0 :(得分:7)
不要使用字符串格式将值插入SQL。对于datetime
对象,默认字符串格式适用于MySQL,但这只是偶然性和运气。
在这种情况下,不要使用原始SQL并让SQLAlchemy将datetime对象转换为后端数据库可以理解的内容:
from sqlalchemy import or_
session.query(Employee).filter(
or_(Employee.end_date == None, Employee.end_date >= datetime.now())
).all()
即使使用原始SQL,我也会使用sqlalchemy生成该SQL并使用绑定参数:
from sqlalchemy.sql.expression import bindparam, column
from sqlalchemy.types import DateTime
from sqlalchemy import or_
dtnow = bindparam('dtnow', datetime.now(), DateTime)
end_date = column('enddate', DateTime)
session.query(Employee).\
filter(or_(end_date == None, end_date >= dtnow)).all()
对于您的数据库后端,无论后端是什么,该过滤器表达式都会转换为正确的转义SQL。如果未设置后端,则表达式为:
>>> str(or_(end_date == None, end_date >= dtnow))
'enddate IS NULL OR enddate >= :dtnow'
并且datetime.now()
值将在执行时作为SQL参数传递给后端数据库游标。
最后一种方法是使用text()
type:
from sqlalchemy.sql.expression import bindparam, text
dtnow = bindparam('dtnow', datetime.now(), DateTime)
session.query(Employee).\
filter(text('end_date is NULL or end_date >= :dtnow', bindparams=[dtnow])).all()
否则我会避免混合原始SQL和SQLAlchemy ORM。仅使用原始SQL与数据库连接:
conn = session.connection()
conn.execute(text('SELECT * FROM t_employee WHERE end_date IS NULL OR end_date>=:dtnow'),
dtnow=datetime.now())