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

https://blog.csdn.net/xuezhangjun0121/article/details/103993135

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
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()
————————————————
版权声明:本文为CSDN博主「Saggitarxm」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/xuezhangjun0121/article/details/103993135

  

posted @   山顶听风  阅读(798)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
点击右上角即可分享
微信分享提示