Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

ASP.NET 手動綁定 GridView 到 Oracle:不靠智慧型控制項的做法

GridView 若交給資料來源控制項(SqlDataSource/EntityDataSource)代勞,很多細節會被藏起來。需要完全掌握查詢時機與資料集的時候,手動綁定反而更可控。以下示範在 Web Forms 中透過 OracleClient 取資料並綁到 GridView。

Page_Load 只在首次載入時取資料

用 IsPostBack 判斷,避免每次回傳都重查一次資料庫——這是按鈕事件、分頁、排序會用到的基本防護:

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        BindData();
    }
}

BindData 的實作

protected void BindData()
{
    string conStr = "Data Source=emsdb;Persist Security Info=True;User ID=emsuser;Password=***;Unicode=True";
    OracleConnection conn = new OracleConnection(conStr);

    string QueryStr = "select * from T_department";
    OracleDataAdapter adapter = new OracleDataAdapter(QueryStr, conn);

    DataSet ds = new DataSet();
    adapter.Fill(ds);

    GridView1.DataSource = ds.Tables[0];
    GridView1.DataKeyNames = new string[] { "id" };
    GridView1.DataBind();
}

幾個實務上該調整的地方

  • 連線字串不要寫在程式碼裡。請放到 Web.config 的 connectionStrings 區段並加密,原始範例那種明文帳密寫死在 Page 後端的做法,一旦 Repository 外洩等於直接送出資料庫權限。
  • 別用 select *。明確列出欄位,除了避免資料表變動時炸掉,也能減少不必要的傳輸量。
  • 用參數化查詢。若要帶入條件,請改用 OracleCommand 搭配 OracleParameter,用字串拼接 SQL 就是 SQL Injection 的入口。
  • using 區段:需要 System.Data.OracleClient 與 System.Data;命名空間則依專案結構放在例如 work1.sysconfig 之下,Page 類別繼承 System.Web.UI.Page。
  • DataKeyNames 的用途:設為主鍵欄位(此例為 id)之後,刪除或更新時可從 GridView.DataKeys[rowIndex] 取得主鍵值,不必依賴顯示欄位的位置。
  • 若資料量可能很大,記得改用分頁查詢(Oracle 12c 以後可用 OFFSET FETCH),不要一次把整張表 Fill 進 DataSet。

整體流程就是:建立連線 → DataAdapter 帶 SQL 填充 DataSet → 指定 DataSource → 設定 DataKeyNames → DataBind。手動綁定的好處是每一步都在你手上,壞處是資源釋放與錯誤處理都要自己負責,別忘了把連線納入 using 或 finally 中關閉。

Copyright © Linux教程網 All Rights Reserved