2012-02-20 66 views
0

在这里我的问题,我使用asp.net为我的网站,我得到一个书籍列表并显示它们,一切都好。现在我尝试这种书籍的标题,作者或其他属性进行排序,我使用这个代码:ASP.NET MySQL订单通过提供错误的结果

public static IDataReader GetPageByCritere(
     int pageNumber, 
     int pageSize, 
     out int totalPages, 
     string critere, 
     string direction) 
    { 
     int pageLowerBound = (pageSize * pageNumber) - pageSize; 
     totalPages = 1; 
     int totalRows = GetCount(); 

     if (pageSize > 0) totalPages = totalRows/pageSize; 

     if (totalRows <= pageSize) 
     { 
      totalPages = 1; 
     } 
     else 
     { 
      int remainder; 
      Math.DivRem(totalRows, pageSize, out remainder); 
      if (remainder > 0) 
      { 
       totalPages += 1; 
      } 
     } 

     StringBuilder sqlCommand = new StringBuilder(); 
     sqlCommand.Append("SELECT * "); 
     sqlCommand.Append("FROM a_book "); 
     //sqlCommand.Append("WHERE "); 
     sqlCommand.Append("ORDER BY ?Critere ?direction "); 
     sqlCommand.Append("LIMIT ?PageSize "); 

     if (pageNumber > 1) 
     { 
      sqlCommand.Append("OFFSET ?OffsetRows "); 
     } 

     sqlCommand.Append(";"); 

     MySqlParameter[] arParams = new MySqlParameter[4]; 

     arParams[0] = new MySqlParameter("?PageSize", MySqlDbType.Int32); 
     arParams[0].Direction = ParameterDirection.Input; 
     arParams[0].Value = pageSize; 

     arParams[1] = new MySqlParameter("?OffsetRows", MySqlDbType.Int32); 
     arParams[1].Direction = ParameterDirection.Input; 
     arParams[1].Value = pageLowerBound; 

     arParams[2] = new MySqlParameter("?Critere", MySqlDbType.VarChar, 50); 
     arParams[2].Direction = ParameterDirection.Input; 
     arParams[2].Value = critere; 

     arParams[3] = new MySqlParameter("?direction", MySqlDbType.VarChar, 50); 
     arParams[3].Direction = ParameterDirection.Input; 
     arParams[3].Value = direction; 

     return MySqlHelper.ExecuteReader(
      GetReadConnectionString(), 
      sqlCommand.ToString(), 
      arParams); 
    } 
} 

当我执行此代码书没有得到整理,我得到的第一个项目列表不排序,在这里我的SqlCommand和arParams与标题分拣为例: 的SqlCommand

{SELECT * FROM a_book ORDER BY ?Critere ?direction LIMIT ?PageSize ;} 

arParams:

{?PageSize} : 20 {?OffsetRows} : -20 {?Critere} title {?direction} DESC 

请大家帮忙,我没有找到任何解决方案。

回答

1

不幸的是,这用于在MySql中工作,但行为发生了变化 - 请参见http://bugs.mysql.com/bug.php?id=31474。现在它在这方面的行为与Oracle和SQL Server相似。

相反,你可能要考虑通过基于标准建立订单 - 希望,你的搜索标准字符串不是由用户输入或从用户输入源,否则你就必须防范SQL注入

如果你的标准由一列的,那么你可以简单地这样做:

sqlCommand.Append(String.Format("ORDER BY {0} {1}", Critere, direction)) 

如果搜索标准是多圆柱状的,那么你可能要考虑通过你的排序标准列向列表。

这也涵盖这里:Parameter in order by clause doesn't order -mysql, C#

+0

THX你的答复,我使用 字符串str固定它= “ORDER BY” +搜索标准+ “” +方向; sqlCommand.Append(str); 和我们一样: sqlCommand.AppendFormat(“ORDER BY {0} {1}”,Critere,方向) 非常感谢。 – 2012-02-20 13:29:21