ConditonHelper
在网上其实已经有很多类似这种拼接sql条件的类,但是没有看到一个让我感觉完全满意的这样的类。最近看到 http://www.cnblogs.com/xtdhb/p/3811956.html 这博客,觉得这思路很好,但是个人觉得这样用起来比较麻烦,所以借鉴了这位兄弟的思路自己改进了一下,这样可以很方便地实现任何的组合条件。
以下是ConditionHelper类的代码:
#region public enum Comparison
public enum Comparison
{
/// <summary>
/// 等于号 =
/// </summary>
Equal,
/// <summary>
/// 不等于号 <>
/// </summary>
NotEqual,
/// <summary>
/// 大于号 >
/// </summary>
GreaterThan,
/// <summary>
/// 大于或等于 >=
/// </summary>
GreaterOrEqual,
/// <summary>
/// 小于 <
/// </summary>
LessThan,
/// <summary>
/// 小于或等于 <=
/// </summary>
LessOrEqual,
/// <summary>
/// 模糊查询 Like
/// </summary>
Like,
/// <summary>
/// 模糊查询 Not Like
/// </summary>
NotLike,
/// <summary>
/// is null
/// </summary>
IsNull,
/// <summary>
/// is not null
/// </summary>
IsNotNull,
/// <summary>
/// in
/// </summary>
In,
/// <summary>
/// not in
/// </summary>
NotIn,
/// <summary>
/// 左括号 (
/// </summary>
OpenParenthese,
/// <summary>
/// 右括号 )
/// </summary>
CloseParenthese,
Between,
StartsWith,
EndsWith
}
#endregion public class ConditionHelper
{
#region 变量定义
string parameterPrefix = "@";
string parameterKey = "P";
/// <summary>
/// 用来拼接SQL语句
/// </summary>
StringBuilder conditionBuilder = new StringBuilder();
/// <summary>
/// 为True时表示字段为空或者Null时则不作为查询条件
/// </summary>
bool isExcludeEmpty = true;
/// <summary>
/// 是否生成带参数的sql
/// </summary>
bool isBuildParameterSql = true;
/// <summary>
/// 参数列表
/// </summary>
public List<SqlParameter> parameterList = new List<SqlParameter>();
int index = ; const string and = " AND ";
const string or = " OR ";
#endregion #region 构造函数 /// <summary>
/// 创建ConditionHelper对象
/// </summary>
/// <param name="isBuildParameterSql">是否生成带参数的sql</param>
/// <param name="isExcludeEmpty">为True时表示字段为空或者Null时则不作为查询条件</param>
public ConditionHelper(bool isBuildParameterSql = true, bool isExcludeEmpty = true)
{
this.isBuildParameterSql = isBuildParameterSql;
this.isExcludeEmpty = isExcludeEmpty;
}
#endregion #region 公共方法
/// <summary>
/// 添加and 条件
/// </summary>
/// <param name="fieldName">字段名称</param>
/// <param name="comparison">比较符类型</param>
/// <param name="fieldValue">字段值</param>
/// <returns>返回ConditionHelper</returns>
public ConditionHelper AddAndCondition(string fieldName, Comparison comparison, params object[] fieldValue)
{
conditionBuilder.Append(and);
this.AddCondition(fieldName, comparison, fieldValue);
return this;
} /// <summary>
/// 添加or条件
/// </summary>
/// <param name="fieldName">字段名称</param>
/// <param name="comparison">比较符类型</param>
/// <param name="fieldValue">字段值</param>
/// <returns>返回ConditionHelper</returns>
public ConditionHelper AddOrCondition(string fieldName, Comparison comparison, params object[] fieldValue)
{
conditionBuilder.Append(or);
this.AddCondition(fieldName, comparison, fieldValue);
return this;
} /// <summary>
/// 添加and+左括号+条件
/// </summary>
/// <param name="comparison">比较符类型</param>
/// <param name="fieldName">字段名称</param>
/// <param name="fieldValue">字段值,注:Between时,此字段必须填两个值</param>
/// <returns>返回ConditionHelper</returns>
public ConditionHelper AddAndOpenParenthese(string fieldName, Comparison comparison, params object[] fieldValue)
{
this.conditionBuilder.AppendFormat("{0}{1}", and, GetComparisonOperator(Comparison.OpenParenthese));
this.AddCondition(fieldName, comparison, fieldValue);
return this;
} /// <summary>
/// 添加or+左括号+条件
/// </summary>
/// <returns></returns>
/// <param name="comparison">比较符类型</param>
/// <param name="fieldName">字段名称</param>
/// <param name="fieldValue">字段值,注:Between时,此字段必须填两个值</param>
/// <returns>返回ConditionHelper</returns>
public ConditionHelper AddOrOpenParenthese(string fieldName, Comparison comparison, params object[] fieldValue)
{
this.conditionBuilder.AppendFormat("{0}{1}", or, GetComparisonOperator(Comparison.OpenParenthese));
this.AddCondition(fieldName, comparison, fieldValue);
return this;
} /// <summary>
/// 添加右括号
/// </summary>
/// <returns></returns>
public ConditionHelper AddCloseParenthese()
{
this.conditionBuilder.Append(GetComparisonOperator(Comparison.CloseParenthese));
return this;
} /// <summary>
/// 添加条件
/// </summary>
/// <param name="comparison">比较符类型</param>
/// <param name="fieldName">字段名称</param>
/// <param name="fieldValue">字段值,注:Between时,此字段必须填两个值</param>
/// <returns>返回ConditionHelper</returns>
public ConditionHelper AddCondition(string fieldName, Comparison comparison, params object[] fieldValue)
{
//如果选择IsExcludeEmpty为True,并且该字段为空值的话则跳过
if (isExcludeEmpty && string.IsNullOrEmpty(fieldValue.ToString()))
return this; switch (comparison)
{
case Comparison.Equal:
case Comparison.NotEqual:
case Comparison.GreaterThan:
case Comparison.GreaterOrEqual:
case Comparison.LessThan:
case Comparison.LessOrEqual:
this.conditionBuilder.AppendFormat("{0}{1}{2}", GetFieldName(fieldName), GetComparisonOperator(comparison), GetFieldValue(fieldValue[]));
break;
case Comparison.IsNull:
case Comparison.IsNotNull:
this.conditionBuilder.AppendFormat("{0}{1}", GetFieldName(fieldName), GetComparisonOperator(comparison));
break;
case Comparison.Like:
case Comparison.NotLike:
this.conditionBuilder.AppendFormat("{0}{1}{2}", GetFieldName(fieldName), GetComparisonOperator(comparison), GetFieldValue(string.Format("%{0}%", fieldValue[])));
break;
case Comparison.In:
case Comparison.NotIn:
this.conditionBuilder.AppendFormat("{0}{1}({2})", GetFieldName(fieldName), GetComparisonOperator(comparison), string.Join(",", GetFieldValue(fieldValue)));
break;
case Comparison.StartsWith:
this.conditionBuilder.AppendFormat("{0}{1}{2}", GetFieldName(fieldName), GetComparisonOperator(comparison), GetFieldValue(string.Format("{0}%", fieldValue[])));
break;
case Comparison.EndsWith:
this.conditionBuilder.AppendFormat("{0}{1}{2}", GetFieldName(fieldName), GetComparisonOperator(comparison), GetFieldValue(string.Format("%{0}", fieldValue[])));
break;
case Comparison.Between:
this.conditionBuilder.AppendFormat("{0}{1}{2} AND {3}", GetFieldName(fieldName), GetComparisonOperator(comparison), GetFieldValue(fieldValue[]), GetFieldValue(fieldValue[]));
break;
default:
throw new Exception("条件为定义");
}
return this;
} public override string ToString()
{
return this.conditionBuilder.ToString();
} #endregion #region 私有方法
/// <summary>
/// 取得字段值
/// </summary>
/// <param name="fieldValue"></param>
/// <returns></returns>
private string GetFieldValue(params object[] fieldValue)
{
if (isBuildParameterSql == false)
{
if (fieldValue.Length < )
{
return string.Format("'{0}'", fieldValue[]);
}
else
{
return string.Format("'{0}'", string.Join("','", fieldValue));
}
}
else
{
if (fieldValue.Length < )
{
return AddParameter(fieldValue[]);
}
else
{
List<string> parameterNameList = new List<string>();
foreach (var value in fieldValue)
{
parameterNameList.Add(AddParameter(value));
}
return string.Join(",", parameterNameList);
}
}
} /// <summary>
/// 添加参数
/// </summary>
/// <param name="fieldValue"></param>
/// <returns></returns>
private string AddParameter(object fieldValue)
{
index++;
string parameterName = string.Format("{0}{1}{2}", parameterPrefix, parameterKey, index);
parameterList.Add(new SqlParameter()
{
ParameterName = parameterName,
Value = fieldValue
});
return parameterName;
} private string GetFieldName(string fieldName)
{
return string.Format("[{0}]", fieldName);
}
private static string GetComparisonOperator(Comparison comparison)
{
string result = string.Empty;
switch (comparison)
{
case Comparison.Equal:
result = " = ";
break;
case Comparison.NotEqual:
result = " <> ";
break;
case Comparison.GreaterThan:
result = " > ";
break;
case Comparison.GreaterOrEqual:
result = " >= ";
break;
case Comparison.LessThan:
result = " < ";
break;
case Comparison.LessOrEqual:
result = " <= ";
break;
case Comparison.Like:
case Comparison.StartsWith:
case Comparison.EndsWith:
result = " LIKE ";
break;
case Comparison.NotLike:
result = " NOT LIKE ";
break;
case Comparison.IsNull:
result = " IS NULL ";
break;
case Comparison.IsNotNull:
result = " IS NOT NULL ";
break;
case Comparison.In:
result = " IN ";
break;
case Comparison.NotIn:
result = " NOT IN ";
break;
case Comparison.OpenParenthese:
result = " (";
break;
case Comparison.CloseParenthese:
result = ") ";
break;
case Comparison.Between:
result = " BETWEEN ";
break;
}
return result;
}
#endregion }
比如说要实现这样的一个例子:
UserName In ('张三','李四','王五') and Age between 1 and 17 and (Gender='Male' or Gender='Female')
实现代码:
ConditionHelper helper = new ConditionHelper(false);
helper.AddCondition("UserName", Comparison.In, "张三", "李四", "王五")
.AddAndCondition("Age",Comparison.Between,,)
.AddAndOpenParenthese("Gender",Comparison.Equal,"Male")
.AddOrCondition("Gender",Comparison.Equal,"Female")
.AddCloseParenthese();
string condition=helper.ToString();
还有要提一下的是这个类中的isExcludeEmpty变量,这个是借鉴了园子里伍华聪的想法,由于是很早以前看的,具体是哪一篇文章就不太清楚了,有兴趣的可以去他博客http://www.cnblogs.com/wuhuacong/里找下看。这变量在这有什么用呢?不要小看这小小的变量,它让我们在实际中少了很多重复的代码。比如界面上有一个条件文本框txtUserName,那我们一般拼接条件如下:
if(!string.IsNullOrEmpty(txtUserName.Text.Trim())
{
condition=string.Format("UserName like '%{0}%'",txtUserName.Text.Trim())
}
简单说就是每次在拼接条件时都要判断文本框里的值是否为空,只有在不为空的情况才加入条件里去。
现在在ConditonHelper里加了isExcludeEmpty变量,我们在使用的时候就不要加判断了,在ConditionHelper中拼接条件时它会自动去判断,是不是这样让代码变得更简洁?
个人觉得这样用起来还是挺方便的。第一次写文章,写得不好,不过写这文章的主要目的是分享自己的想法,同时也希望能得到大家的指点,个人感觉这个类应该还有很多可以优化的地方,所以以后可能还会修改。
ConditonHelper的更多相关文章
随机推荐
- 图片热区——axure线框图部件库介绍
首先,我们将图片热区组建拖动到axure页面编辑区域 1. 图片热区为页面图片或者其他部件添加热区,添加交互 我们一般在做专题的时候,会遇到一些组合商品,但是又需要单独分别设置连接,如果是2张图片还好 ...
- Keepalived安装工具
装keepalived前,要先检查主机上是否已经安装, ps -ef | grep keepalive 不检查的话.easy把前人装的东西覆盖掉,那么曾经弄的配置文件都没了比較麻烦. 下面都为root ...
- 手机SIM卡无法识别解决方案
SIM卡是工作中测试用的,经常插拔到不同的手机,前两天SIM卡放到手机中都能正常识别,今天插入到另一款手机中发现无法识别.心里糟了,是不是卡坏了,根据之 前的直觉,在公司找了一块橡皮,在SIM卡的芯片 ...
- uva 1374 快速幂计算
#include <iostream> #include <cstdio> #include <cmath> #include <cstring> #i ...
- 关于vs2005 __RPC__out __RPC__in 没有定义编译错误
1. 下载WDK http://www.microsoft.com/en-us/download/details.aspx?id=11800 2. 安装WDK 3. vs2005 设置:工具--> ...
- 【从零学习经典算法系列】分治策略实例——高速排序(QuickSort)
在前面的博文(http://blog.csdn.net/jasonding1354/article/details/37736555)中介绍了作为分治策略的经典实例,即归并排序.并给出了递归形式和循环 ...
- 【ASP.NET Web API教程】3.4 HttpClient消息处理器
原文:[ASP.NET Web API教程]3.4 HttpClient消息处理器 注:本文是[ASP.NET Web API系列教程]的一部分,如果您是第一次看本博客文章,请先看前面的内容. 3.4 ...
- TCP、UDP数据包大小的限制(UDP数据包一次发送多大为好)——数据帧的物理特性决定的,每层都有一个自己的数据头,层层递减
1.概述 首先要看TCP/IP协议,涉及到四层:链路层,网络层,传输层,应用层. 其中以太网(Ethernet)的数据帧在链路层 IP包在网络层 TCP或UDP包在传输层 TCP或UDP中的数据(Da ...
- WM_SYSCOMMAND消息命令整理 good
注意:1. 使用WM_SYSCOMMAND时,鼠标的一些消息可能会受到影响,比如不能响应MouseUp事件,可以在窗口中捕获WM_SYSCOMMAND消息,并判断消息的CommandType来判断消息 ...
- listview改变选中行字体颜色
[android]listview改变选中行字体颜色 目标:选中item,其字体设置为#3197FF,未选中的,其字体为#FFFFFF 与listvew设置选中行item背景图片一样,使用select ...