在网上其实已经有很多类似这种拼接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的更多相关文章

随机推荐

  1. 树——axure线框图部件库介绍

    终于到最后一个组件的介绍了!到这里基础的应用应该算完成了!  1. 拖动树组件,到页面编辑区域  2.添加节点,可以添加子节点也可以在该节点的前后添加平级节点  3. 编辑节点图标 做好上面的那一步, ...

  2. ASP.NET - 服务器控件button 先执行js 再执行后台的方法

    关于button这个服务器控件,我一直想减少它向服务器提交数据.那些检测,还是在客户端实现就好了.这就需要javascript,但是我发现仅仅有javascript还是不够的.button服务器控件的 ...

  3. 进阶:案例六: Context Menu(静态 与 动态)

    实现: 1.add: 2.delete 3.add2 实现步骤: 1.新建属性display_text 2.创建layout 3.代码部分: add事件: METHOD onactionadd . D ...

  4. VC++ WIN32 sdk实现按钮自绘详解.

    网上找了很多,可只是给出代码,没有详细解释,不便初学者理解.我就抄回冷饭.把这个再拿出来说说. 实例图片:    首先建立一个标准的Win32 Application 工程.选择a simple Wi ...

  5. js实现class样式的修改、添加及删除的方法

    本文实例讲述了js实现class样式的修改.添加及删除的方法.分享给大家供大家参考.具体分析如下: 比较常见的js前端功能,通过修改标签的className实现相应的功能. 具体代码如下: <t ...

  6. hdu5086——Revenge of Segment Tree

    Revenge of Segment Tree Time Limit: 4000/2000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/ ...

  7. Python标准库:内置函数dict(iterable, **kwarg)

    本函数是从可迭代对象来创建新字典.比方一个元组组成的列表,或者一个字典对象. 样例: #dict() #以键对方式构造字典 d1 = dict(one = 1, two = 2, a = 3) pri ...

  8. centos 安装ganglia监控工具

    一个.ganglia基本介绍 ganglia它是一个分布式监控系统,那里有两个Daemon,每间:clientGangliaMonitoring Daemon (gmond)和服务端GangliaMe ...

  9. VC图形绘制双缓存的代码复用性讨论

    在前文中已经讨论了如何实现界面绘制双缓存的问题,前文网址如下: http://www.2cto.com/kf/201111/112429.html 双缓存的主要思路是:先把图形绘制到内存DC中,然后再 ...

  10. Shell printf 命令

    Shell printf 命令 printf 命令模仿 C 程序库(library)里的 printf() 程序. 标准所定义,因此使用printf的脚本比使用echo移植性好. printf 使用引 ...