ADO.NET在开发中的部分使用方法和技巧 -2

来源:互联网 发布:数据库上机实验报告 编辑:程序博客网 时间:2024/04/28 22:31
  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.关闭连接。 

 

上述代码片段调用了以下存储过程。

CREATE PROCEDURE DATGetProductDetailsSPOutput north face jackets
@ProductName nvarchar(40) OUTPUT, 
@UnitPrice money OUTPUT AS SELECT @ProductName = ProductName, 
@UnitPrice = UnitPrice FROM Products WHERE ProductID = @ProductID GO 
如何使用 SqlDataReader 来检索单个行
可以使用 SqlDataReader对象来检索单个行,尤其是可以从返回的数据流中检索需要的列值。以下代码片段对此进行了说明。
原创粉丝点击