2007年12月11日 星期二

ADO.NET 2.0資料提供者

ADO.NET支援多種資料來源類型的存取功能。在它的架構圖中,開發人員可以由資料來源而決定使用何種.NET資料提供者(.NET Data Provider)。不過當程式需要開發某些資料庫工具時,可能需要讓使用者決定資料提供者,那麼開發人員就不能直接在程式中寫死使用某種提供者(例如:SqlClient或OleDb…等)。本文將介紹ADO.NET資料提供者的一個重要類別 – DbProviderFactory。

01

圖是ADO.NET之.NET 資料提供者架構圖,開發人員依據資料來源決定使用何種資料提供者。例如,SQL Server 7.0以上版本的資料來源使用System.Data.SqlClient命名空間下的類別。程式碼列表1,是使用SQL Server .NET Data Provider連到本機的Northwind資料庫存取產品資料表。

Visual Basic
Dim cn As New SqlConnection("server=.;database=northwind;integrated security=true")
Dim com As New SqlCommand("Select ProductID, ProductName From Products", cn)
Dim reader As SqlDataReader
cn.Open()
reader = com.ExecuteReader()
Dim bindingSrc As New BindingSource
bindingSrc.DataSource = reader
DataGridView1.DataSource = bindingSrc
cn.Close()

C#

SqlConnection cn = new SqlConnection("server=.;database=northwind;integrated security=true");
SqlCommand com = new SqlCommand("Select ProductID, ProductName From Products", cn);
SqlDataReader reader ;
cn.Open();
reader = com.ExecuteReader();
BindingSource bindingSrc = new BindingSource();
bindingSrc.DataSource = reader;
cn.Close();
DataGridView1.DataSource = bindingSrc;


詳全文...

沒有留言:

張貼留言