当前位置导航:炫浪网>>网络学院>>编程开发>>Visual C#教程

C#中一套生成sql条件的类

    在进行sql查询的时候,有时候要进行很多条件限制,自己来拼写SQLwhere条件容易出错,而且判断条件复杂,后期维护困难,基于这个原因我在一个小项目中写了一套生成sql条件的类。总共包括一个Condition类,与两个枚举型类型(LogicOper,CompareOper)
代码如下:
    public class Condition
    {
        static string [] logicOpers = new string[]{\"and\",\"or\"};
        static string [] compareOpers = new string[]{\">\",\"<\",\"<=\",\">=\",\"=\",\"<>\",\"like\",\"not like\",\"in\"};

        string compareOper=null;
        string name=null;
        string templateName = null;
        string valType=null;
        object val=null;
        public Condition(CompareOper co,string valType,string name,object val)
        {
            this.compareOper = compareOpers[(int)co];
            this.name = name;
            templateName = name;
            this.valType = valType;
            this.val = val;
        }
        public Condition(CompareOper co,string valType,string name,object val,string templateName)
        {
            this.compareOper = compareOpers[(int)co];
            this.name = name;
            this.templateName = templateName;
            this.valType = valType;
            this.val = val;
        }
        public Condition(){}

        public string toSqlString() [Page]
        {
            string []  arr1 =  (string[])operaters.ToArray(\"\".GetType());
            Condition []  arr2 =  (Condition[])conditions.ToArray((new Condition()).GetType());
            
            StringBuilder outStr = new StringBuilder();

            int count=0;
            if(name!=null&&val!=null)
            {
                outStr.Append(name);
                outStr.Append(\" \");
                outStr.Append(compareOper);
                outStr.Append(\" \");
                if(valType.ToLower()==\"int\"
                    ||valType.ToLower()==\"float\"
                    ||valType.ToLower()==\"double\"
                    ||valType.ToLower()==\"bool\"
                    ||valType.ToLower()==\"number\"

     )
                {
                    outStr.Append(val);
                } [Page]
                else if(valType.ToLower()==\"string\")
                {
                    string tmp = (string)val;
                    outStr.Append(\"’\"+tmp.Replace(\"’\",\"’’\")+\"’\");
                }
                else if(valType.ToLower()==\"date\")
                {
                    DateTime dt = (DateTime)val;
                    outStr.Append(\"’\"+dt.ToString(\"yyyy-MM-dd\")+\"’\");
                }
                else if(valType.ToLower()==\"datetime\")
                {
                    DateTime dt = (DateTime)val;
                    outStr.Append(\"’\"+dt.ToString(\"yyyy-MM-dd hh:mm:ss.fff\")+\"’\");
                }
                else
                {
                    string tmp = val.ToString();
                    outStr.Append(\"’\"+tmp.Replace(\"’\",\"’’\")+\"’\"); [Page]
                }
                count++;
            }

共2页 首页 上一页 1 2 下一页 尾页 跳转到
相关内容
赞助商链接