首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> ASP.NET 基礎 >> 關於ASP.NET

ASP.NET 2.0 資料教程 72:TableAdapter 連接字串與命令逾時層級設定擴充(ADO.NET 連接/命令物件深入操作)

     編輯:關於ASP.NET

前言

Typed DataSet 的 TableAdapter 封裝 ADO.NET 細節,但有時需直接存取 SqlConnection、SqlCommand 設定(如連接字串、CommandTimeout)。本文示範擴充 ProductsTableAdapter 暴露這些屬性。

ADO.NET 核心物件回顧

  • SqlConnection:資料庫連接(連接字串、狀態、交易)。
  • SqlCommand:SQL 命令/預存程序(CommandText、Parameters、CommandTimeout、Transaction)。
  • SqlDataAdapter:橋接 Command 與 DataTable(Fill、Update)。

TableAdapter 內部結構

  • 每個 TableAdapter 擁有 Connection 屬性(內部 SqlConnection)。
  • 每個查詢方法對應一個 SqlCommand(SelectCommand, InsertCommand, UpdateCommand, DeleteCommand)。

擴充 ProductsTableAdapter 步驟

  1. 開啟 Northwind.xsd → 右鍵 ProductsTableAdapter → View Code(建立 Partial Class)。
  2. 新增公開屬性暴露內部設定:
public partial class ProductsTableAdapter
{
    // 取得/設定連接字串
    public string ConnectionString
    {
        get { return this.Connection.ConnectionString; }
        set { this.Connection.ConnectionString = value; }
    }

    // 取得/設定命令逾時 (秒)
    public int CommandTimeout
    {
        get { return this.CommandCollection[0].CommandTimeout; }
        set 
        {
            foreach (SqlCommand cmd in this.CommandCollection)
                cmd.CommandTimeout = value;
        }
    }
}

使用範例

var adapter = new ProductsTableAdapter();
adapter.ConnectionString = "新連接字串"; // 動態切換資料庫
adapter.CommandTimeout = 120; // 延長逾時至 2 分鐘
var products = adapter.GetProducts();

結語

透過 Partial Class 擴充 TableAdapter,可在不修改設計工具產生代碼的前提下,靈活控制 ADO.NET 連接/命令層級設定,滿足動態切換資料庫、長時間查詢等進階需求。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved