ADO.NET入門 五大你需要知道的對象
1. ADO.NET 3.0 用于訪問和操作數(shù)據(jù)的兩個主要組件是: .NET Framework 數(shù)據(jù)提供程序 (虛線框內(nèi)) 和
.NET Framework 數(shù)據(jù)提供程序是專門為數(shù)據(jù)操作以及快速、只進、只讀訪問數(shù)據(jù)而設計的組件。
ADO.NET DataSet 是專門為獨立于任何數(shù)據(jù)源的數(shù)據(jù)訪問而設計的。
對象 |
說明 |
---|---|
Connection |
建立與特定數(shù)據(jù)源的連接。 所有 Connection 對象的基類均為 |
Command |
對數(shù)據(jù)源執(zhí)行命令。 公開 Parameters,并可在 Transaction 范圍內(nèi)從 Connection 執(zhí)行。 所有 Command 對象的基類均為 |
DataReader |
從數(shù)據(jù)源中讀取只進且只讀的數(shù)據(jù)流。 所有 DataReader 對象的基類均為 |
DataAdapter |
使用數(shù)據(jù)源填充 DataSet 并解決更新。 所有 DataAdapter 對象的基類均為 |
注意:新手面試經(jīng)常會遇到考這樣的題:ADO.NET 的五大對象,就是 上面四種 + DataSet 要牢牢記住哦。后期開發(fā)也經(jīng)常用到。
2. Connection 對象(只介紹SqlConnection和JDBC)
使用connection連接的時候記得打開、關閉(返回連接池),建議使用using,這樣就不會忘記關了,將自動斷開連接,即使發(fā)生無法處理的異常。
- using (SqlConnection connection = new SqlConnection(connectionString))
- {
- connection.Open();
- ....
- }
ODBC 比較麻煩 請參考微軟技術文檔:http://support.microsoft.com/kb/310988 (我很少用到)
- using (OdbcConnection connection =
- new OdbcConnection(connectionString))
- {
- connection.Open();
- ....
- }
3.Command對象
命令 |
返回值 |
---|---|
ExecuteReader |
返回一個 DataReader 對象。 |
ExecuteScalar |
返回數(shù)據(jù)庫查詢出來的第一行第一列。 |
ExecuteNonQuery |
執(zhí)行增刪改命令。 |
ExecuteXMLReader |
返回 |
下面用一個實例講解Connection 和 Command、DataReader以及儲存過程和參數(shù)的設置:
(1.)下載安裝微軟提供的Northwind數(shù)據(jù)庫:
/Files/Simcoder/微軟提供的數(shù)據(jù)庫.rar 含幫助文檔 簡單容易操作 數(shù)據(jù)庫安裝后 文件默認在C盤 然后附加即可
(2.)找到提供的存儲過程:(本實例 使用倒數(shù)第二個 SalesByCategory 存儲過程做演示)
(3.)簡單查看一下存儲過程的代碼,其實通過名字都能知道大概做什么用
- ---------------------- *創(chuàng)*建*存*儲*過*程* -----------------------
- set ANSI_NULLS ON
- set QUOTED_IDENTIFIER ON
- go
- ALTER PROCEDURE [dbo].[SalesByCategory] --修改存儲過程[SalesByCategory]
- @CategoryName nvarchar(15), @OrdYear nvarchar(4) = '1998' --設置參數(shù) (以下的實現(xiàn)暫不用管)
- AS
- IF @OrdYear != '1996' AND @OrdYear != '1997' AND @OrdYear != '1998'
- BEGIN
- SELECT @OrdYear = '1998'
- END
- SELECT ProductName,
- TotalPurchase=ROUND(SUM(CONVERT(decimal(14,2), OD.Quantity * (1-OD.Discount) * OD.UnitPrice)), 0)
- FROM [Order Details] OD, Orders O, Products P, Categories C
- WHERE OD.OrderID = O.OrderID
- AND OD.ProductID = P.ProductID
- AND P.CategoryID = C.CategoryID
- AND C.CategoryName = @CategoryName
- AND SUBSTRING(CONVERT(nvarchar(22), O.OrderDate, 111), 1, 4) = @OrdYear
- GROUP BY ProductName
- ORDER BY ProductName
- ---------------------- *執(zhí)*行*存*儲*過*程* -----------------------
- USE [Northwind]
- GO
- DECLARE @return_value int
- EXEC @return_value = [dbo].[SalesByCategory]
- @CategoryName = N'Produce',
- @OrdYear = N'1998'
- SELECT 'Return Value' = @return_value
- GO
--需要設置@CategoryName,@OrdYear(可以不設置 為空上面有判斷)參數(shù)值
查詢結(jié)果是:
(4.)新建一個控制臺的應用程序 代碼如下:
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Data.SqlClient;
- using System.Data;
- namespace ConsoleApplication1
- {
- class Program
- {
- static void Main(string[] args)
- {
- GetSalesByCategory("server=.;uid=sa;pwd=123456;database=Northwind", "Produce");//在這里就默認設置了 參數(shù)@CategoryName參數(shù)的值為 Produce
- }
- static void GetSalesByCategory(string connectionString,string categoryName)
- {
- using (SqlConnection connection = new SqlConnection(connectionString))
- {
- SqlCommand command = new SqlCommand();
- command.Connection = connection;
- command.CommandText = "SalesByCategory"; //CommandType 屬性設置為 StoredProcedure 時,CommandText 屬性應設置為存儲過程的名稱
- command.CommandType = CommandType.StoredProcedure; //設置執(zhí)行類型為存儲過程
- SqlParameter parameter = new SqlParameter();
- parameter.ParameterName = "@CategoryName";//指定存儲過程中的那個參數(shù)
- parameter.SqlDbType = SqlDbType.NVarChar;//指定數(shù)據(jù)類型
- parameter.Direction = ParameterDirection.Input;//指定參數(shù)為輸入
- parameter.Value = categoryName;
- command.Parameters.Add(parameter);
- connection.Open();
- SqlDataReader reader = command.ExecuteReader();
- if (reader.HasRows)//判斷是否有數(shù)據(jù)行
- {
- while (reader.Read())
- {
- Console.WriteLine("{0}: {1:C}", reader[0], reader[1]);
- }
- }
- else
- {
- Console.WriteLine("No rows found.");
- }
- reader.Close();//記得關閉
- Console.ReadLine();
- }
- }
- }
- }
前面簡單提到了 Connection 、DataReader、Comand以及參數(shù)和存儲過程的用法,現(xiàn)在更加深入的學習。
1.DataReader的用法:
DataReader 從數(shù)據(jù)庫中檢索只讀、只進的數(shù)據(jù)流。查詢結(jié)果在查詢執(zhí)行時返回,在并存儲在客戶端的網(wǎng)絡緩沖區(qū)中,直到您使用 DataReader 的 Read 方法對它們發(fā)出請求。 使用 DataReader 可以提高應用程序的性能,原因是它只要數(shù)據(jù)可用就立即檢索數(shù)據(jù),并且(默認情況下)一次只在內(nèi)存中存儲一行,減少了系統(tǒng)開銷。
例子見上一篇即可,說說使用DataReader的心得,在做項目中,有時候一個實體類中的字段又是另外一個實體雷,存在外鍵的關系。如下實體類源碼 中就有2個這樣的關系(高亮代碼):
- using System;
- using System.Collections.Generic;
- using System.Text;
- namespace BookShop.Model
- {
- [Serializable]
- public class Book
- {
- /// <summary>
- /// 圖書編號
- /// </summary>
- private int id;
- public int Id
- {
- get { return id; }
- set { id = value; }
- }
- /// <summary>
- /// 圖書標題
- /// </summary>
- private string title;
- public string Title
- {
- get { return title; }
- set { title = value; }
- }
- /// <summary>
- /// 圖書作者
- /// </summary>
- private string author;
- public string Author
- {
- get { return author; }
- set { author = value; }
- }
- /// <summary>
- /// 圖書出版社
- /// </summary>
- private Publisher publisher;
- public Publisher Publisher
- {
- get { return publisher; }
- set { publisher = value; }
- }
- /// <summary>
- /// 圖書出版日期
- /// </summary>
- private DateTime publishDate;
- public DateTime PublishDate
- {
- get { return publishDate; }
- set { publishDate = value; }
- }
- /// <summary>
- /// 圖書ISBN編號
- /// </summary>
- private string isbn;
- public string Isbn
- {
- get { return isbn; }
- set { isbn = value; }
- }
- /// <summary>
- /// 圖書總字數(shù)
- /// </summary>
- private int wordsCount;
- public int WordsCount
- {
- get { return wordsCount; }
- set { wordsCount = value; }
- }
- /// <summary>
- /// 圖書價格
- /// </summary>
- private decimal unitPrice;
- public decimal UnitPrice
- {
- get { return unitPrice; }
- set { unitPrice = value; }
- }
- /// <summary>
- /// 圖書描述
- /// </summary>
- private string contentDescription;
- public string ContentDescription
- {
- get { return contentDescription; }
- set { contentDescription = value; }
- }
- /// <summary>
- /// 圖書作者描述
- /// </summary>
- private string authorDescription;
- public string AuthorDescription
- {
- get { return authorDescription; }
- set { authorDescription = value; }
- }
- /// <summary>
- /// 圖書作者評語
- /// </summary>
- private string editorComment;
- public string EditorComment
- {
- get { return editorComment; }
- set { editorComment = value; }
- }
- /// <summary>
- /// 圖書目錄
- /// </summary>
- private string toc;
- public string Toc
- {
- get { return toc; }
- set { toc = value; }
- }
- /// <summary>
- /// 圖書的分類
- /// </summary>
- private Category category;
- public Category Category
- {
- get { return category; }
- set { category = value; }
- }
- /// <summary>
- /// 圖書點擊
- /// </summary>
- private int clicks;
- public int Clicks
- {
- get { return clicks; }
- set { clicks = value; }
- }
- }
- }
如果是這種關系,使用Datareader 就可能會出現(xiàn)異常,因為當代碼讀到 外鍵的時候,外鍵也要使用connection連接 這時就會拋出異常,所以
與數(shù)據(jù)進行動態(tài)交互,例如綁定到 Windows 窗體控件或組合并關聯(lián)來自多個源的數(shù)據(jù)。
對數(shù)據(jù)執(zhí)行大量的處理,而不需要與數(shù)據(jù)源保持打開的連接,從而將該連接釋放給其他客戶端使用。就使用DataSet或DataTable比較合適。
也許你不太明白,但是你可以這樣簡單的記住,當實體類或數(shù)據(jù)庫設計存在主外鍵關系的時候,使用Datareader就要謹慎了! 不過也沒關系,很多經(jīng)驗都是從Debug學到的。
就好像微軟的視頻一樣,為愛Debug。
原文標題:ADO.NET快速上手(一)
鏈接:http://www.cnblogs.com/Simcoder/archive/2010/05/03/1726295.html