62,074
社区成员
发帖
与我相关
我的任务
分享
public static Product[] SearchProducts(string keyword, int categoryID, int pageSize, int pageIndex, out int total)
{
OleDbConnection connection = new OleDbConnection(ConnectionString);
// 建立查询,查出满足条件产品的总数
OleDbCommand countCommand = connection.CreateCommand();
countCommand.CommandText = "SELECT COUNT(ProductID) FROM tblProducts ";
string where = "WHERE Active > 0 ";
if (categoryID > 0)
{
where = where + "AND CategoryID = " + categoryID.ToString() + " ";
}
if (!string.IsNullOrEmpty(keyword))
{
where = where + "AND ProductName LIKE '%" + keyword + "%' ";
}
countCommand.CommandText += where;
DataTable dt = new DataTable();
try
{
connection.Open();
total = (int)countCommand.ExecuteScalar();
if (total < 1) return null; // 没有记录返回空(null)
int maxPageNum = (total % pageSize == 0 ? total / pageSize : total / pageSize + 1);
if (pageIndex < 1) pageIndex = 1;
if (pageIndex > maxPageNum) pageIndex = maxPageNum;
// 建立查询,查出满足条件的产品
OleDbCommand selectCommand = connection.CreateCommand();
selectCommand.CommandText = "SELECT TOP " + (pageSize * pageIndex).ToString() + " ProductID, ProductName FROM tblProducts " + where;
if (pageIndex != 1)
{
selectCommand.CommandText = selectCommand.CommandText + " ORDER BY ProductID ASC ";
string tmpCommand = string.Format("select top {0} ProductID, ProductName from (select top {1} ProductID, ProductName from ({2}) order by ProductID DESC) order by ProductID asc"
, pageSize, pageIndex == maxPageNum ? total - (pageIndex - 1) * pageSize : pageSize, selectCommand.CommandText);
selectCommand.CommandText = tmpCommand;
}
OleDbDataAdapter oda = new OleDbDataAdapter();
oda.SelectCommand = selectCommand;
oda.Fill(dt);
Product[] products = null;
if (dt != null)
{
products = new Product[dt.Rows.Count];
for (int i = 0; i < products.Length; i++)
{
products[i] = new Product();
products[i].ProductID = Convert.ToInt32(dt.Rows[i]["ProductID"]);
products[i].ProductName = dt.Rows[i]["ProductName"] == DBNull.Value ? "" : dt.Rows[i]["ProductName"].ToString();
}
}
return products;
}
catch
{
throw;
}
finally
{
if (ConnectionState.Closed != connection.State)
connection.Close();
}
}