在网上其实已经有很多类似这种拼接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. shell 调用mysql 存储过程判断真假

    mysql> create table TBL_STUDENT(id int,name char(10),CLASSNO int,BIRTH datetime); Query OK, 0 row ...

  2. (升级版)Spark从入门到精通(Scala编程、案例实战、高级特性、Spark内核源码剖析、Hadoop高端)

    本课程主要讲解目前大数据领域最热门.最火爆.最有前景的技术——Spark.在本课程中,会从浅入深,基于大量案例实战,深度剖析和讲解Spark,并且会包含完全从企业真实复杂业务需求中抽取出的案例实战.课 ...

  3. Basic4android:多功能的Android应用软件快速开发平台

    Basic4android 是目前最简单.最强大的Android平台快速应用开发工具. ( "Basic4android is the simplest and most powerful ...

  4. Eclipse中提高Android SDK Manager下载速度方法

    在Windows-System32-drivers-ect目录下找到hosts文件 打开hosts文件(用记事本打开就可以),在文件以下填上一下内容: 203.208.46.146 www.googl ...

  5. JSP的学习(5)——语法知识三之include指令

    本篇继续来对JSP语法中的JSP指令进行学习,在<JSP的学习(3)——语法知识二之page指令>中,已经介绍了JSP指令的书写格式和page指令的详细信息,所以在这一篇中我们会对JSP指 ...

  6. 在Mac OS X苹果lion系统上制作USB启动盘

    本文翻译自:http://evan.borgstrom.ca/post/1314205955/osx-bootable-usb-from-iso 我也就不按照原文上一句句的翻译了,只说几个比较重要的步 ...

  7. 基于特定值来推断隐藏显示元素的jQuery插件

    jQuery-Visibly是一款小巧简单的jQuery隐藏显示元素插件.该插件依据某个元素的值,例如以下拉框的值.输入框的值等来推断是否显示某个指定的元素. 用于推断的值能够是单个值,或者是多个值, ...

  8. Android四大组件--Broadcast Receiver具体解释

    本文主要讲述了: 一.BroadcastReceiver概述: 二.BroadcastReceiver事件分类 三.BroadcastReceiver事件的编程流程 四.两类BroadcastRece ...

  9. 汉字转拼音再转ASCII

    汉字能够转成拼音.能够在转成ASCII码,然后就能够转成十六进制数,再就能够转成0和1组成的二进制帧了! 比方说: 我爱你 -> wo ai ni -> 119 111 32 97 105 ...

  10. 爱的歌我uhegierhiuerh5怕哦一

    http://www.huihui.cn/share/8424421 http://www.huihui.cn/share/8424375 http://www.huihui.cn/share/842 ...