在進行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() { 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); } 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("’","’’")+"’"); } count++; }