如何使用 SqlDataReader 来检索单个行可以使用 SqlDataReader 对象来检索单个行,尤其是可以从返回的数据流中检索需要的列值。以下代码片段对此进行了说明。 void GetProductDetailsUsingReader( 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( "DATGetProductDetailsReader", conn ); cmd.CommandType = CommandType.StoredProcedure; // Establish stored proc parameters. // @ProductID int INPUT SqlParameter paramProdID = cmd.Parameters.Add( "@ProductID", ProductID ); paramProdID.Direction = ParameterDirection.Input; conn.Open(); using( SqlDataReader reader = cmd.ExecuteReader() ) { if( reader.Read() ) // Advance to the one and only row { // Return output parameters from returned data stream ProductName = reader.GetString(0); UnitPrice = reader.GetDecimal(1); } } }}使用 SqlDataReader 对象来返回单个行 1. 建立 SqlCommand 对象。 2. 打开连接。 3. 调用 SqlDataReader 对象的 ExecuteReader 方法。 4. 通过 SqlDataReader 对象的类型化访问器方法(在这里,为 GetString 和 GetDecimal)来检索输出参数。 上述代码片段调用了以下存储过程。 CREATE PROCEDURE DATGetProductDe[1] [2] [3] [4] [5] [6] [7] [8] 下一页
|