萬盛學電腦網

 萬盛學電腦網 >> 網絡編程 >> 編程語言綜合 >> ADO.NET使用方法和技巧

ADO.NET使用方法和技巧

   以下代碼闡明了如何使用 SqlDataAdapter 對象發出可生成 DataSet 或 DataTable 的命令。它從 SQL Server Northwind 數據庫中檢索一組產品類別。

  using System.Data;

  using System.Data.SqlClient;

  public DataTable RetrieveRowsWithDataTable()

  {

  using ( SqlConnection conn = new SqlConnection(connectionString) )

  {

  conn.Open();

  SqlCommand cmd = new SqlCommand("DATRetrieveProducts", conn);

  cmd.CommandType = CommandType.StoredProcedure;

  SqlDataAdapter adapter = new SqlDataAdapter( cmd );

  DataTable dataTable = new DataTable("Products");

  adapter .Fill(dataTable);

  return dataTable;

  }

  }

  使用 SqlAdapter 生成 DataSet 或 DataTable

  1.

  創建一個 SqlCommand 對象以調用該存儲過程,並將其與一個 SqlConnection 對象(顯示)或連接字符串(不顯示)相關聯。

  2.

  創建一個新的 SqlDataAdapter 對象並將其與 SqlCommand 對象相關聯。

  3.

  創建一個 DataTable(也可以創建一個 DataSet)對象。使用構造函數參數來命名 DataTable。

  4.

  調用 SqlDataAdapter 對象的 Fill 方法,用檢索到的行填充 DataSet 或 DataTable。

  如何使用 SqlDataReader 來檢索多個行

  以下代碼片段闡明了可檢索多個行的 SqlDataReader 方法。

  using System.IO;

  using System.Data;

  using System.Data.SqlClient;

  public SqlDataReader RetrieveRowsWithDataReader()

  {

  SqlConnection conn = new SqlConnection(

  "server=(local);Integrated Security=SSPI;database=northwind");

  SqlCommand cmd = new SqlCommand("DATRetrieveProducts", conn );

  cmd.CommandType = CommandType.StoredProcedure;

  try

  {

  conn.Open();

  // Generate the reader. CommandBehavior.CloseConnection causes the

  // the connection to be closed when the reader object is closed

  return( cmd.ExecuteReader( CommandBehavior.CloseConnection ) );

  }

  catch

  {

  conn.Close();

  throw;

  }

  }

  // Display the product list using the console

  private void DisplayProducts()

  {

  SqlDataReader reader = RetrieveRowsWithDataReader();

  try

  {

  while (reader.Read())

  {

  Console.WriteLine("{0} {1} {2}",

  reader.GetInt32(0).ToString(),

  reader.GetString(1) );

  }

  }

  finally

  {

  reader.Close(); // Also closes the connection due to the

  // CommandBehavior enum used when generating the reader

  }

  }

  使用 SqlDataReader 檢索行

  1.

  創建一個用來執行存儲過程的 SqlCommand 對象,並將其與一個 SqlConnection 對象相關聯。

  2.

  打開連接。

  3.

  通過調用 SqlCommand 對象的 ExecuteReader 方法創建一個 SqlDataReader 對象。

  4.

  要從流中讀取數據,請調用 SqlDataReader 對象的 Read 方法來檢索行,並使用類型化訪問器方法(如 GetInt32 和 GetString 方法)來檢索列值。

  5.

  使用完讀取器後,請調用其 Close 方法。

  如何使用 XmlReader 檢索多個行

  可以使用 SqlCommand 對象來生成 XmlReader 對象,後者可提供對 XML 數據的基於流的只進訪問。命令(通常為存儲過程)必須產生基於 XML 的結果集,對於 SQL Server 2000 而言,該結果集通常包含一個帶有有效 FOR XML 子句的 SELECT 語句。以下代碼片段闡明了該方法:

  public void RetrieveAndDisplayRowsWithXmlReader()

  {

  using( SqlConnection conn = new SqlConnection(connectionString) )

  {;

  SqlCommand cmd = new SqlCommand("DATRetrieveProductsXML", conn );

  cmd.CommandType = CommandType.StoredProcedure;

  try

  {

  conn.Open();

  XmlTextReader xreader = (XmlTextReader)cmd.ExecuteXmlReader();

  while ( xreader.Read() )

  {

  if ( xreader.Name == "PRODUCTS" )

  {

  string strOutput = xreader.GetAttribute("ProductID");

  strOutput += " ";

  strOutput += xreader.GetAttribute("ProductName");

  Console.WriteLine( strOutput );

  }

  }

  xreader.Close(); // XmlTextReader does not support IDisposable so it can't be

  // used within a using keyword

  }

  }

  上述代碼使用了以下存儲過程:

  CREATE PROCEDURE DATRetrieveProductsXML

  AS

  SELECT * FROM PRODUCTS

  FOR XML AUTO

  GO

  使用 XmlReader 檢索 XML 數據

  1.

  創建一個 SqlCommand 對象來調用可生成 XML 結果集的存儲過程(例如,在 SELECT 語句中使用 FOR XML 子句)。將該 SqlCommand 對象與某個連接相關聯。

  2.

  調用 SqlCommand 對象的 ExecuteXmlReader 方法,並且將結果分配給只進 XmlTextReader 對象。當您不需要對返回的數據進行任何基於 XML 的驗證時,這是應該使用的最快類型的 XmlReader 對象。

  3.

  使用 XmlTextReader 對象的 Read 方法來讀取數據。

  如何使用存儲過程輸出參數來檢索單個行

  借助於命名的輸出參數,可以調用在單個行內返回檢索到的數據項的存儲過程。以下代碼片段使用存儲過程來檢索 Northwind 數據庫的 Products 表中包含的特定產品的產品名稱和單價。

  void GetProductDetails( int ProductID,

  out string ProductName, out decimal UnitPrice )

  {

  using( SqlConnection conn = new SqlConnection(

  "server=(local);Integrated Security=SSPI;database=Northwind") )

  {

  // Set up the command object used to execute the stored proc

  SqlCommand cmd = new SqlCommand( "DATGetProductDetailsSPOutput", conn )

  cmd.CommandType = CommandType.StoredProcedure;

  // Establish stored proc parameters.

  // @ProductID int INPUT

  // @ProductName nvarchar(40) OUTPUT

  // @UnitPrice money OUTPUT

  // Must explicitly set the direction of output parameters

  SqlParameter paramProdID =

  cmd.Parameters.Add( "@ProductID", ProductID );

  paramProdID.Direction = ParameterDirection.Input;

  SqlParameter paramProdName =

  cmd.Parameters.Add( "@ProductName", SqlDbType.VarChar, 40 );

  paramProdName.Direction = ParameterDirection.Output;

  SqlParameter paramUnitPrice =

  cmd.Parameters.Add( "@UnitPrice", SqlDbType.Money );

  paramUnitPrice.Direction = ParameterDirection.Output;

  conn.Open();

  // Use ExecuteNonQuery to run the command.

  // Although no rows are returned any mapped output parameters

  // (and potentially return values) are populated

  cmd.ExecuteNonQuery( );

  // Return output parameters from stored proc

  ProductName = paramProdName.Value.ToString();

  UnitPrice = (decimal)paramUnitPrice.Value;

  }

  }

  使用存儲過程輸出參數來檢索單個行

  1.

  創建一個 SqlCommand 對象並將其與一個 SqlConnection 對象相關聯。

  2.

  通過調用 SqlCommand 的 Parameters 集合的 Add 方法來設置存儲過程參數。默認情況下,參數都被假設為輸入參數,因此必須顯式設置任何輸出參數的方向。

  注 一種良好的習慣做法是顯式設置所有參數(包括輸入參數)的方向。

  3.

  打開連接。

  4.

  調用 SqlCommand 對象的 ExecuteNonQuery 方法。這將填充輸出參數(並可能填充返回值)。

  5.

  通過使用 Value 屬性,從適當的 SqlParameter 對象中檢索輸出參數。

  6.

  關閉連接。

  上述代碼片

copyright © 萬盛學電腦網 all rights reserved