ADO.NET 數據庫訪問之數據分頁

程序儘可能地降低其使用的複雜性,它的優點是使用方便。現在這個程序還有一個缺點,那就是第讀取一頁的數據,都要打開一次數據庫,這個問題是可以解決的,那就是要求在不使用之用執行一個Close,關閉數據庫,這是以犧牲程序的安全性爲代價的。各個方面需要權衡利弊。

/******************************************************************************
 * Copryright(c) My Studio Inc. 2008-2009, all rights reserved.
 * 程序名稱:數據庫分頁讀取類
 * 日    期:2008年4月26日
 * 作    者:汪思言
 * 郵    箱:[email protected]
 *
 * 使用說明:
 * 首先創建一個MyDataPage類實例mypage,然後設置數據庫連接串、查詢表、查詢列、查詢條件、
 * 排序條件等。然後執行mypage.DoPaging(),注意檢查其返回值,返回真表示分頁成功,否則
 * 應查看mypage.ErrMessage屬性。成功後,就可以使用mypage.GetData(<頁編號>)讀取數據了.
 *
 * 示例:
 * 
 * using MyLibrary.DataAccess;
 * MyDataPage myPage = new MyDataPage(
 *   "provider=sqloledb;server=(local);uid=sa;pwd=oohacker;database=Northwind",
 *   "Product",
 *   "ProductId,ProductName",
 *   "SupplierId<>1",
 *   "SupplierId ASC, ProductId DESC",
 *   20);
 * 
 * if (myPage.DoPaging()) 
 * {
 *   Console.Write("Total Records: {0}  Total Pages: {1} ",
 *     myPage.RecordCount,
 *     myPage.PageCount);
 *   
 *   for (int i=1; i<=myPage.PageCount; ++i)
 *   {
 *     Console.Write("Page {0} ", i);
 *     DataTable table = myPage.GetData(i);
 *     for (int j=0; j<table.Rows.Count; ++j)
 *     {
 *       Console.Write("#{0}:{1} ", 
 *         table.Rows[j]["ProductId"],
 *         table.Rows[j]["ProductName"]);
 *     }
 *   }
 * }
 * else
 * {
 *   Console.Write("分頁失敗!原因:{0} ",  myPage.ErrMessage);
 * }
 *
 ****************************************************************************
*/



using System;
using System.Text;
using System.Data;
using System.Data.OleDb;
using System.Collections;

namespace MyLibrary.DataAccess
{
  
public class MyDataPage
  
{
    
成員變量

    
構造函數

    
// 獲取和設置頁面大小
    public int PageSize
    
{
      
set
      
{
        pageSize 
= (value >=10 && value <= 1000? value : defaltPageSize;
        isDirty 
= true;
      }

      
get
      
{
        
return pageSize;
      }

    }


    
// 獲取記錄數
    public int RecordCount
    
{
      
get return recordCount; }
    }


    
// 獲取頁面數
    public int PageCount
    
{
      
get return pageCount; }
    }


    
// 獲取和設置表名
    public string Table
    
{
      
set this.table = value.Trim(); isDirty = true; }
      
get return this.table; }
    }


    
// 獲取和設置要讀取的列
    public string Columns
    
{
      
set 
      
{
        
this.columns = value.Trim(); 
        
if (this.columns == ""this.columns = "*";
        isDirty 
= true;
      }

      
get return this.columns; }
    }


    
// 獲取和設置讀取的條件
    public string Conditions
    
{
      
set this.conditions = value.Trim(); isDirty = true; }
      
get return this.conditions; }
    }


    
// 獲取或設置排序
    public string Orders
    
{
      
set this.orders = value.Trim(); isDirty = true; }
      
get return this.orders; }
    }


    
// 獲取設置連接字串
    public string ConnectionString
    
{
      
set this.connectionString = value; isDirty = true; }
      
get return this.connectionString; }
    }


    
// 獲取SQL查詢命令
    public string SelectCommand
    
{
      
get 
      
{
        StringBuilder command 
= new StringBuilder(256);
        command.AppendFormat(
"select {0} from [{1}] ", columns, table);
        
if (conditions != "")
        
{
          command.AppendFormat(
" where {0}", conditions);
        }

        
if (orders != "")
        
{
          command.AppendFormat(
" order by {0}", orders);
        }

        
return command.ToString();
      }

    }


    
// 獲取異常信息
    public string ErrMessage
    
{
      
get return errorMessage; }
    }


    
// 執行分頁
    public bool DoPaging()
    
{
      errorMessage 
= "";
      
// 生成統計SQL
      StringBuilder sqlParas = new StringBuilder(256);
      sqlParas.AppendFormat(
"from [{0}] ", table);
      
if (conditions != "")
      
{
        sqlParas.AppendFormat(
" where {0}", conditions);
      }

      String sqlCount 
= "select count(*) as [RowCount] " + sqlParas.ToString();

      
// 開始統計
      OleDbConnection conn = new OleDbConnection(connectionString);
      
try
      
{
        conn.Open();
      }

      
catch (Exception e)
      
{
        errorMessage 
= e.Message;
        
return false;
      }


      
// 執行分頁獲取記錄數和頁面數信息
      OleDbDataAdapter adapter = new OleDbDataAdapter();
      DataSet ds 
= new DataSet();
      
try
      
{
        
// 統計總記錄數, 得出記錄總和頁面數
        adapter.SelectCommand = new OleDbCommand(sqlCount, conn);
        adapter.Fill(ds, 
"Count");
        recordCount 
= (int)(ds.Tables["count"].Rows[0])["RowCount"];
        ds.Clear();

        pageCount 
= recordCount / pageSize + (recordCount % pageSize > 0 ? 1 : 0);
      }

      
catch (Exception e)
      
{
        errorMessage 
= e.Message;
        
return false;
      }

      
finally
      
{
        conn.Close();
      }


      isDirty 
= false;
      
return true;
    }


    
// 執行分頁查詢
    public DataTable GetData(int page)
    
{
      errorMessage 
= "";
      
if (isDirty)
      
{
        errorMessage 
= "查詢條件已改變,必須先執行分頁才能再次讀取數據";
        
return null;
      }


      
// 開始查詢
      OleDbConnection conn = new OleDbConnection(connectionString);
      
try
      
{
        conn.Open();
      }

      
catch (Exception e)
      
{
        errorMessage 
= e.Message;
        
return null;
      }


      
// 執行分頁並讀取數據
      OleDbDataAdapter adapter = new OleDbDataAdapter();
      DataSet ds 
= new DataSet();
      
try
      
{
        
// 執行分頁並讀取數據
        if (page > pageCount)
        
{
          errorMessage 
= "頁面數溢出!";
          
return null;
        }

        
int recordStartIndex = (page - 1* pageSize;
        adapter.SelectCommand 
= new OleDbCommand(this.SelectCommand, conn);
        adapter.Fill(ds, recordStartIndex, pageSize, table);
      }

      
catch (Exception e)
      
{
        errorMessage 
= e.Message;
        
return null;
      }

      
finally
      
{
        conn.Close();
      }

      
return ds.Tables[table];
    }

  }

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章