日期:2014-05-19  浏览次数:20445 次

|M| 在做查询的时候大家都是怎么来写SQL的 下面是我的写法看看大家怎么写

public   static   DataTable   Search(Int32   ID,String   Name,DateTime   Brith)
{
      StringBuilder   IWhere=new   StringBuilder();
      IWhere.Append( "   Where   1=1 ");
      if(ID!=-1)
      {
            IWhere.Append( "   And   ID   =   "+   ID);
      }
      if(Name   != " ")
      {
            IWhere.Append( "   And   Name   like   '% "   +   Name   +   "% ' ");
      }
      if(Brith!=DateTime.MinValue)
      {
            IWhere.Append( "   And   Brith   =   ' "   +   Brith   +   " ' ");
      }
      String   Sql= "Select   *   From   Studen ";
      Sql+=IWhere.ToString();
      ...
}
页面查询

//数据初始
Int32   ID=   -1;
String   Name   = " ";
DateTime   Brith   =DateTime.MinValue;
//数据赋值
ID=Convert.ToInt32(txt_ID.Text);
Name=txt_Name.Text;
Brith=Convert.ToDateTime(txt_Brith.Text);
//执行查询
DataTable   dt=Search(ID,Name,Brith);

上面哪里还有得改进的因为这个最长出现的代码
我想有更好的写法
请大家指点

谢谢

------解决方案--------------------
IWhere.Append(ID!==-1? " And ID = "+ ID: " ");//使用三元运算符
------解决方案--------------------
我要写更复杂拉

不过提几个建议

1. 是birth 不是Brith
2. 习惯上参数应该是小写字母开头

还有,为什么要拼SQL语句呢?用参数数组解决不是更好
------解决方案--------------------
楼主 这样做 很 危险
要么在使用 函数前 对传入的参数 进行sql 过滤

public static string FilterSQL(string text)
{
string validSql = " ";
if (text != null)
{
text = text.Replace( "\ " ", "" ");
text = text.Replace( "; ", " ' '; ' ' ");
text = text.Replace( " ' ", " ' ' ");
text = text.Replace( "-- ", " ' '-- ' ' ");

//过滤html
//text = text.Replace( "%25 ", " ");
//text = text.Replace( "%0a ", " ");
//text = text.Replace( "%22 ", " ");
//text = text.Replace( "%27 ", " ");
//text = text.Replace( "%5c ", " ");
//text = text.Replace( "%2f ", " ");
//text = text.Replace( "%3c ", " ");
//text = text.Replace( "%3e ", " ");
//text = text.Replace( "%26 ", " ");

//text = text.Replace( " < ", "&lt; ");
//text = text.Replace( "> ", "&gt; ");
validSql = text;
}
return validSql;