演示ADO.NET使用存储过程获取数据

开发 后端
这里就ADO.NET使用简单存储过程获取数据做出了详细的分析,大家仔细阅读,详细一定会给大家带来技术上的提高的。

ADO.NET经过长时间的发展,很多用户都很了解ADO.NET了,这里我发表一下个人理解,和大家讨论讨论。代码并不创建 Connection 对象或 Command 对象。事实上,没有这些对象,ADO.NET 便无法工作,但它们是在后台创建并使用的。实例化 SqlDataAdapter 的代码行传入 SQL 字符串(用于配置后台 Command 对象)和连接字符串(用于配置后台 Connection 对象)。

我们可以将此代码更改为使用显式 Connection 和 Command 对象,以便稍稍远离演示软件。在表单上再放置一个按钮,并将以下代码放到 Click 事件中。

  1. Dim sConnectionString As String = _ 
  2. "server=localhost;uid=sa;pwd=;database=Northwind"  
  3. Dim sSQL As String = "SELECT * FROM Products" 
  4.  
  5. Dim cnNorthwind As New SqlConnection(sConnectionString)  
  6. Dim cmdProducts As New SqlCommand(sSQL, cnNorthwind)  
  7.  
  8. Dim daGetProducts As New SqlDataAdapter(cmdProducts)  
  9. Dim dsProducts As New DataSet()  
  10. daGetProducts.Fill(dsProducts, "Products")  
  11. DataGrid1.DataSource = dsProducts.Tables("Products")  

#T#此代码通过显式创建 Connection 和 Command 对象,并将这些对象附加到 DataAdapter,说明了 DataAdapters 的常用性。通过在实例化 DataAdapter 时传入 cmdProducts,DataAdapter 的 SelectCommand 将自动设置。然后,可以立即使用 DataAdapter 访问数据库。此代码的结果与前一示例中的结果相同。尽管它有点接近真实软件,但由于数据访问是通过 SQL 语句实现的,因此仍然属于演示软件。

ADO.NET使用简单存储过程获取数据

如何将此演示软件更改为ADO.NET使用存储过程?只需更改几行代码。在表单上再放置一个按钮,并将以下代码放到 Click 事件中:

  1. Dim sConnectionString As String = _ 
  2. "server=localhost;uid=sa;pwd=;database=Northwind"  
  3. Dim cnNorthwind As New SqlConnection(sConnectionString)  
  4. Dim cmdProducts As New _  
  5. SqlCommand("十件最贵的产品", cnNorthwind)  
  6. cmdProducts.CommandType = CommandType.StoredProcedure  
  7.  
  8. Dim daGetProducts As New SqlDataAdapter(cmdProducts)  
  9. Dim dsProducts As New DataSet()  
  10. daGetProducts.Fill(dsProducts, "Products")  
  11. DataGrid1.DataSource = dsProducts.Tables("Products")  

实例化 Command 对象时,此代码不使用 SQL 语句并替换为要ADO.NET使用的存储过程名称。此外,Command 对象的 CommandType 属性必须设置为 StoredProcedure。此后的代码与上一个示例非常相似,但它返回不同的数据。存储过程查找十件最贵的产品,并只返回每个产品的名称和价格。

责任编辑:田树 来源: 博客
相关推荐

2009-11-04 09:02:34

ADO.NET _C

2009-11-12 09:51:59

ADO.NET结构

2009-11-11 11:08:03

ADO.NET存储过程

2009-11-04 16:23:09

ADO.NET存储过程

2009-11-13 11:18:22

ADO.NET修改数据

2009-11-04 11:30:35

ADO.NET Dat

2009-10-29 10:00:53

ADO.NET数据集

2009-11-03 15:13:13

ADO .NET存储过

2009-11-12 10:06:01

ADO.NET读取数据

2009-11-13 10:01:50

ADO.NET CAS

2009-12-28 15:11:36

ADO.NET专家

2009-12-22 16:50:44

ADO.NET元素

2009-11-12 10:24:19

ADO.NET代码

2009-11-11 11:27:02

ADO.NET存储过程

2009-11-12 13:26:56

使用ADO.NET参数

2009-11-11 13:38:04

ADO.NET sql

2010-01-04 13:47:18

ADO.NET数据集

2009-10-29 10:20:19

ADO.NET使用

2009-12-31 09:18:23

ADO.NET对象模型

2009-12-30 10:49:32

ADO.NET Ent
点赞
收藏

51CTO技术栈公众号