哈喽,你好啊,我是雷工!
在项目开发中涉及到许多通过多个条件勾选来实现动态的多个条件查询的情况,
此节记录多条件查询的后台代码编写,以下为学习笔记。
01 实现原理
通过界面输入框输入或者下拉框下拉选择任意查询条件,在后台将所填写或选择的条件进行组合,然后进行数据查询。
02 实现步骤
2.1、数据访问层
根据三层架构,首先编写数据访问层;
编程思路:
①:定义基本的SQL语句;
②:定义组合条件语句;
③:将基本的SQL语句和动态的条件语句组合起来;
④:执行组合的查询语句;
⑤:封装查询结果;
⑥:返回查询结果;
编程代码如下:
/// <summary>
/// 根据多个查询条件动态组合查询
/// </summary>
/// <param name="typeId">账号类型</param>
/// <param name="accountName">账号名称</param>
/// <returns></returns>
public List<Account>QueryAccount(int typeId,string accountName )
{
//①:定义基本的SQL语句
string sql = "select AccountId,AccountName,AccountContent,originality,TypeId,AuthorName from Account";
sql += " inner join Author on Author.AuthorId=Auccount.AuthorId where";
//②:定义组合条件
string whereSql = string.Empty;
if(typeId!=-1)
{
whereSql += "and TypeId=" + typeId;
}
if(accountName!="")//此处没有必要检查null,因为通过文本框传递的数据永远不可能为null
{
whereSql += #34; and AccountName like '{accountName}%'";
}
//在实际项目开发中,如果还有其他的条件,在此处继续添加if判断;
//③:将动态的查询条件和前面的基本查询语句结合
sql += whereSql.Substring(3);//把第一个and去掉后,组合sql语句
//④:执行查询语句
SqlDataReader reader = SQLHelper.GetReader(sql);
//⑤:封装结果
List<Account> list = new List<Account>();
while (reader.Read())
{
list.Add(new Account
{
AccountId = (int)reader["AccountId"],
AccountName = reader["AccountName"].ToString(),
AccountContent = reader["AccountContent"].ToString(),
originality = (int)reader["originality"],
TypeId = (int)reader["TypeId"],
AuthorId = (int)reader["AuthorId"],
AuthorName = reader["AuthorName"].ToString()
});
}
reader.Close();
//⑥:返回结果
return list;
}
2.2、细节调整
①:前面练习时Account没加AuthorId列,重新创建了一下Account表;
②:数据库添加完列,在实体类添加对应字段
2.3、业务逻辑层
此次练习业务比较简单,只是传递作用;
在业务逻辑层LeiGongBLL的AccountManager类中添加如下代码:
/// <summary>
/// 根据多个查询条件动态组合查询
/// </summary>
/// <param name="typeId">账号类型</param>
/// <param name="accountName">账号名称</param>
/// <returns></returns>
public List<Account> QueryAccount(int typeId, string accountName)
{
return accountServices.QueryAccount(typeId, accountName);
}
03 后记
以上为多条件动态查询的所有后端代码的练习,接下来继续学习UI层的实现;
有感兴趣的小伙伴可以继续围观。
本文暂时没有评论,来添加一个吧(●'◡'●)