sqlalchemy.exc.ArgumentError: Textual SQL expression '' should be explicitly declared as text('')

文章目录

        • 1. 背景与问题
        • 2. 解决办法
        • 3. 参考连接

1. 背景与问题

安装了scrapyd环境,编译器为python3.5。用db.session.query.filter()语句进行数据库查询操作。之前没有报错的代码,现在报错了。

报错信息
sqlalchemy.exc.ArgumentError: Textual SQL expression ‘’ should be explicitly declared as text(’’)

错误原因
因为安装的python包依赖sqlalchmy版本不一致造成的。参考:解决 sqlalchemy报Textual SQL expression should be explicitly declared as text的错误
sqlalchemy.exc.ArgumentError: Textual SQL expression '' should be explicitly declared as text('')_第1张图片

2. 解决办法

# 原代码
db_sessioin_query = db.session.query(DataTable.data_id,
        DataTable.con_title, DataTable.con_time, DataTable.con_author, DataTable.data_address,
        DataTable.data_spidername, DataTable.category)
        
filter_result = db_sessioin_query.filter(
        and_(DataTable.con_time > s_time if s_time != "" else "",
             DataTable.con_time < e_time,
             DataTable.con_title.like("%" + p_title + "%") if p_title is not None else "",
             DataTable.con_author.like("%" + p_author + "%") if p_author  is not None else "",
             DataTable.data_address.like("%" + p_website + "%") if p_website is not None else "")
        ).order_by(desc(DataTable.data_id)).limit(limit).offset(offset).all()

把"“变成text(”")

# 修改后       
filter_result = db_sessioin_query.filter(
    and_(DataTable.con_time > s_time if s_time != "" else "",
         DataTable.con_time < e_time,
         DataTable.con_title.like("%" + p_title + "%") if p_title is not None else text(""),
         DataTable.con_author.like("%" + p_author + "%") if p_author is not None else text(""),
         DataTable.data_address.like("%" + p_website + "%") if p_website is not None else text(""))
).order_by(desc(DataTable.data_id)).limit(limit).offset(offset).all()

3. 参考连接

CSDN:解决 sqlalchemy报Textual SQL expression should be explicitly declared as text的错误

你可能感兴趣的:(python)