转至繁体中文版     | 网站首页 | 图文教程 | 资源下载 | 站长博客 | 图片素材 | 武汉seo | 武汉网站优化 | 
最新公告:     敏韬网|教学资源学习资料永久免费分享站!  [mintao  2008年9月2日]        
您现在的位置: 学习笔记 >> 图文教程 >> 站长学院 >> Web开发 >> 正文
总结:ADO.NET在开发中的部分使用方法和技巧         ★★★★

总结:ADO.NET在开发中的部分使用方法和技巧

作者:闵涛 文章来源:闵涛的学习笔记 点击数:2351 更新时间:2009/4/23 10:36:00

如何使用 SqlDataAdapter 来检索多个行

以下代码阐明了如何使用 SqlDataAdapter 对象发出可生成 DataSetDataTable 的命令。它从 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 方法来检索行,并使用类型化访问器方法(如 GetInt32GetString 方法)来检索列值。

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.

通过调用 SqlCommandParameters 集合的 Add 方法来设置存储过程参数。默认情况下,参数都被假设为输入参数,因此必须显式设置任何输出参数的方向。

一种良好的习惯做法是显式设置所有参数(包括输入参数)的方向。

3.

打开连接。

4.

调用 SqlCommand 对象的 ExecuteNonQuery 方法。这将填充输出参数(并可能填充返回值)。

5.

通过使用 Value 属性,从适当的 SqlParameter 对象中检索输出参数。

6.

关闭连接。

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

CREATE PROCEDURE DATGetProductDetailsSPOutput
@ProductID int,
@ProductName nvarchar(40) OUTPUT,
@UnitPrice money OUTPUT
AS
SELECT @ProductName = ProductName, 
       @UnitPrice = UnitPrice 
FROM Products 
WHERE ProductID = @ProductID
GO

如何使用 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
        Prod

[1] [2] [3]  下一页


[C语言系列]NET 中C#的switch语句的语法  [系统软件]托拽Explore中的文件到VB.net的窗口
[系统软件]Boost库在XP+Visual C++.net中的安装  [常用软件]新配色面板:Paint.Net3.0RC1官方下载
[常用软件]用内建的“Net Meeting”聊天  [VB.NET程序]Henry的VB.NET之旅(三)—共享成员
[VB.NET程序]Henry的VB.NET之旅(二)—构造与析构  [VB.NET程序]Henry的VB.NET之旅(一)—失踪的窗体
[VB.NET程序]在托盘上显示Balloon Tooltip(VB.NET)  [VB.NET程序]Henry手记-VB.NET中动态加载Treeview节点(二)
教程录入:mintao    责任编辑:mintao 
  • 上一篇教程:

  • 下一篇教程:
  • 【字体: 】【发表评论】【加入收藏】【告诉好友】【打印此文】【关闭窗口
      注:本站部分文章源于互联网,版权归原作者所有!如有侵权,请原作者与本站联系,本站将立即删除! 本站文章除特别注明外均可转载,但需注明出处! [MinTao学以致用网]
      网友评论:(只显示最新10条。评论内容只代表网友观点,与本站立场无关!)

    同类栏目
    · Web开发  · 网页制作
    · 平面设计  · 网站运营
    · 网站推广  · 搜索优化
    · 建站心得  · 站长故事
    · 互联动态
    更多内容
    热门推荐 更多内容
  • 没有教程
  • 赞助链接
    更多内容
    闵涛博文 更多关于武汉SEO的内容
    500 - 内部服务器错误。

    500 - 内部服务器错误。

    您查找的资源存在问题,因而无法显示。

    | 设为首页 |加入收藏 | 联系站长 | 友情链接 | 版权申明 | 广告服务
    MinTao学以致用网

    Copyright @ 2007-2012 敏韬网(敏而好学,文韬武略--MinTao.Net)(学习笔记) Inc All Rights Reserved.
    闵涛 投放广告、内容合作请Q我! E_mail:admin@mintao.net(欢迎提供学习资源)

    站长:MinTao ICP备案号:鄂ICP备11006601号-18

    闵涛站盟:医药大全-武穴网A打造BCD……
    咸宁网络警察报警平台