sqlalchemy - sqlalchemy中执行原生sql - 传参方式避免了sql注入

def get_data_all(user_id, name, start_time, end_time, page=1, limit=10):
    """
    sqlalchemy orm 执行原生sql语句
    :return:
    """
    try:
        # 项目数据列表
        conditions = dict()
        base_sql_pre = "select * from table1 p  where p.status = 1  and p.user_id = :user_id"

        conditions.update({"user_id": user_id})
        if start_time:
            start_time_sql = " and p.create_time >= :start_time"
            conditions.update({"start_time": start_time})
        else:
            start_time_sql = ""
        if end_time:
            end_time_sql = " and p.create_time <= :end_time"
            conditions.update({"end_time": end_time})
        else:
            end_time_sql = ""
        if name:
            name_sql = " and p.name like concat('%', :name, '%')"
            conditions.update({"name": str(name).strip()})
        else:
            name_sql = ""
        # 分页
        offset_size = (page - 1) * limit
        page_sql = " limit :limit_size offset :offset_size"
        conditions.update({
            "limit_size": limit,
            "offset_size": offset_size
        })

        # 组合sql
        select_sql = base_sql_pre + start_time_sql + end_time_sql + name_sql + page_sql
        cursor = db.session.execute(select_sql, conditions)
        res = cursor.fetchall()

        # 总数
        total_count_sql = "select count(id) from table1 p where p.status = 1 and p.user_id = :user_id" + start_time_sql + end_time_sql + name_sql
        conditions.pop("limit_size")
        conditions.pop("offset_size")
        cursor = db.session.execute(total_count_sql, conditions)
        total_count = cursor.fetchall()[0][0]
        return res, total_count
    except Exception:
        traceback.print_exc()

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值