• C#知识|账号管理系统:多条件动态查询条件的编写。


    哈喽,你好啊,我是雷工!

    项目开发中涉及到许多通过多个条件勾选来实现动态的多个条件查询的情况,

    此节记录多条件查询的后台代码编写,以下为学习笔记。

    01 实现原理

    通过界面输入框输入或者下拉框下拉选择任意查询条件,在后台将所填写或选择的条件进行组合,然后进行数据查询。

    02 实现步骤

    2.1、数据访问层

    根据三层架构,首先编写数据访问层;

    编程思路:

    ①:定义基本的SQL语句;

    ②:定义组合条件语句;

    ③:将基本的SQL语句和动态的条件语句组合起来;

    ④:执行组合的查询语句;

    ⑤:封装查询结果;

    ⑥:返回查询结果;

    编程代码如下:

    1. ///
    2. /// 根据多个查询条件动态组合查询
    3. ///
    4. /// 账号类型
    5. /// 账号名称
    6. ///
    7. public ListQueryAccount(int typeId,string accountName )
    8. {
    9.     //①:定义基本的SQL语句
    10.     string sql = "select AccountId,AccountName,AccountContent,originality,TypeId,AuthorName from Account";
    11.     sql += " inner join Author on Author.AuthorId=Auccount.AuthorId where";
    12.     //②:定义组合条件
    13.     string whereSql = string.Empty;
    14.     if(typeId!=-1)
    15.     {
    16. whereSql += "and TypeId=" + typeId;
    17.     }
    18.     if(accountName!="")//此处没有必要检查null,因为通过文本框传递的数据永远不可能为null
    19.     {
    20. whereSql += $" and AccountName like '{accountName}%'";
    21.     }
    22.     //在实际项目开发中,如果还有其他的条件,在此处继续添加if判断;
    23.     //③:将动态的查询条件和前面的基本查询语句结合
    24.     sql += whereSql.Substring(3);//把第一个and去掉后,组合sql语句
    25.     //④:执行查询语句
    26.     SqlDataReader reader = SQLHelper.GetReader(sql);
    27.     //⑤:封装结果
    28.     List list = new List();
    29.     while (reader.Read())
    30.     {
    31. list.Add(new Account
    32. {
    33.     AccountId = (int)reader["AccountId"],
    34.     AccountName = reader["AccountName"].ToString(),
    35.     AccountContent = reader["AccountContent"].ToString(),
    36.     originality = (int)reader["originality"],
    37.     TypeId = (int)reader["TypeId"],
    38.     AuthorId = (int)reader["AuthorId"],
    39.     AuthorName = reader["AuthorName"].ToString()
    40. });
    41.     }
    42.     reader.Close();
    43.     //⑥:返回结果
    44.     return list;
    45. }

    2.2、细节调整

    ①:前面练习时Account没加AuthorId列,重新创建了一下Account表;

    ②:数据库添加完列,在实体类添加对应字段

    2.3、业务逻辑层

    此次练习业务比较简单,只是传递作用;

    在业务逻辑层LeiGongBLL的AccountManager类中添加如下代码:

    1. ///
    2. /// 根据多个查询条件动态组合查询
    3. ///
    4. /// 账号类型
    5. /// 账号名称
    6. ///
    7. public List QueryAccount(int typeId, string accountName)
    8. {
    9.     return accountServices.QueryAccount(typeId, accountName);
    10. }

    03 后记

    以上为多条件动态查询的所有后端代码的练习,接下来继续学习UI层的实现;

    有感兴趣的小伙伴可以继续围观。

  • 相关阅读:
    9月15日作业
    HTTP 常⻅的状态码有哪些,以及适⽤场景
    Dubbo(分布式框架·上)
    【C++】手撕STL系列——stack,queue篇
    Spring创建复杂对象
    java生成随机数的三种写法
    Node.js的基本使用(三)数据库与身份认证
    Java Instrumentation插桩技术
    【分布式任务调度】二、Elastic-Job详细介绍
    opencv读取摄像头并读取时间戳
  • 原文地址:https://blog.csdn.net/u013097500/article/details/140466713