演示ADO.NET使用存儲(chǔ)過程獲取數(shù)據(jù)
ADO.NET經(jīng)過長(zhǎng)時(shí)間的發(fā)展,很多用戶都很了解ADO.NET了,這里我發(fā)表一下個(gè)人理解,和大家討論討論。代碼并不創(chuàng)建 Connection 對(duì)象或 Command 對(duì)象。事實(shí)上,沒有這些對(duì)象,ADO.NET 便無(wú)法工作,但它們是在后臺(tái)創(chuàng)建并使用的。實(shí)例化 SqlDataAdapter 的代碼行傳入 SQL 字符串(用于配置后臺(tái) Command 對(duì)象)和連接字符串(用于配置后臺(tái) Connection 對(duì)象)。
我們可以將此代碼更改為使用顯式 Connection 和 Command 對(duì)象,以便稍稍遠(yuǎn)離演示軟件。在表單上再放置一個(gè)按鈕,并將以下代碼放到 Click 事件中。
- Dim sConnectionString As String = _
- "server=localhost;uid=sa;pwd=;database=Northwind"
- Dim sSQL As String = "SELECT * FROM Products"
- Dim cnNorthwind As New SqlConnection(sConnectionString)
- Dim cmdProducts As New SqlCommand(sSQL, cnNorthwind)
- Dim daGetProducts As New SqlDataAdapter(cmdProducts)
- Dim dsProducts As New DataSet()
- daGetProducts.Fill(dsProducts, "Products")
- DataGrid1.DataSource = dsProducts.Tables("Products")
#T#此代碼通過顯式創(chuàng)建 Connection 和 Command 對(duì)象,并將這些對(duì)象附加到 DataAdapter,說(shuō)明了 DataAdapters 的常用性。通過在實(shí)例化 DataAdapter 時(shí)傳入 cmdProducts,DataAdapter 的 SelectCommand 將自動(dòng)設(shè)置。然后,可以立即使用 DataAdapter 訪問數(shù)據(jù)庫(kù)。此代碼的結(jié)果與前一示例中的結(jié)果相同。盡管它有點(diǎn)接近真實(shí)軟件,但由于數(shù)據(jù)訪問是通過 SQL 語(yǔ)句實(shí)現(xiàn)的,因此仍然屬于演示軟件。
ADO.NET使用簡(jiǎn)單存儲(chǔ)過程獲取數(shù)據(jù)
如何將此演示軟件更改為ADO.NET使用存儲(chǔ)過程?只需更改幾行代碼。在表單上再放置一個(gè)按鈕,并將以下代碼放到 Click 事件中:
- Dim sConnectionString As String = _
- "server=localhost;uid=sa;pwd=;database=Northwind"
- Dim cnNorthwind As New SqlConnection(sConnectionString)
- Dim cmdProducts As New _
- SqlCommand("十件最貴的產(chǎn)品", cnNorthwind)
- cmdProducts.CommandType = CommandType.StoredProcedure
- Dim daGetProducts As New SqlDataAdapter(cmdProducts)
- Dim dsProducts As New DataSet()
- daGetProducts.Fill(dsProducts, "Products")
- DataGrid1.DataSource = dsProducts.Tables("Products")
實(shí)例化 Command 對(duì)象時(shí),此代碼不使用 SQL 語(yǔ)句并替換為要ADO.NET使用的存儲(chǔ)過程名稱。此外,Command 對(duì)象的 CommandType 屬性必須設(shè)置為 StoredProcedure。此后的代碼與上一個(gè)示例非常相似,但它返回不同的數(shù)據(jù)。存儲(chǔ)過程查找十件最貴的產(chǎn)品,并只返回每個(gè)產(chǎn)品的名稱和價(jià)格。