您现在的位置: 网页制作教程网 >> 网络编程 >> c# 教程 >> 文章正文

使用C#创建SQL Server的存储过程

作者:微电脑世…

来源:微电脑世界

热度:

2007-7-2 10:59:01

在方法内我们创建了一个SqlConnection对象,并设置其连接字符串为“context connection = true”。 “上下文连接”可以让你使用当前登录到数据库的用户作为你的登录数据库的验证信息。本例中,ChangeCompanyName()方法将会转换为存储过程,然后保存到Northwind数据库里。所以在这里的“上下文连接”指的就是Northwind数据库。 这样你就不需要再写任何关于登录数据库的验证信息了。

接下来是打开数据库连接。 然后通过设置SqlCommand对象的Connection和CommandText属性,让其执行更新操作。同时,我们还需要设置两个参数。 这样通过调用ExecuteNonQuery()方法就可以执行更新操作了。 再接下来就是关闭连接。

最后,将ExecuteNonQuery()方法的返回值发送到客户端。 当然你也可以不做这一步。现在我们来了解一下SqlContext类的使用。 SqlContext类用于在服务端和客户端之间传递处理结果。本例使用了Send()方法发送一个字符串返回给调用者。


返回从表中读取的一条或多条记录的存储过程
我们在使用存储过程时,经常会SELECT一条或多条记录。 你可以采用两种方法来创建这样的存储过程。

首先我们创建一个名为GetAllCustomers()的方法,代码如下:
[SqlProcedure]
public static void GetAllCustomers()
{
SqlConnection cnn = new SqlConnection
("context connection=true");
cnn.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = cnn;
cmd.CommandText = "select * from customers";
SqlDataReader reader = cmd.ExecuteReader();
SqlContext.Pipe.Send(reader);
reader.Close();
cnn.Close();
}
这个GetAllCustomers()方法用了一个[SqlProcedure]属性来修饰。在方法内创建一个SqlConnection和一个SqlCommand对象。 然后使用ExecuteReader()方法来执行SELECT语句。接下来用Send()方法将取得的SqlDataReader数据发送到客户端。最后就是关闭SqlDataReader和SqlConnection。 在这种方法中,是我们自己创建的SqlDataReader。其实,我们也可以把这个任务交给SqlContext类去完成,代码如下:
[SqlProcedure]
public static void GetCustomerByID
(SqlString CustomerID)
{
SqlConnection cnn = new SqlConnection
("context connection=true");
cnn.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = cnn;
cmd.CommandText = "select * from customers
where customerid=@p1";
SqlParameter p1 = new SqlParameter("@p1", CustomerID);
cmd.Parameters.Add(p1);
SqlContext.Pipe.ExecuteAndSend(cmd);
cnn.Close();
}
GetCustomerByID ()方法需要一个参数 – CustomerID,它将从Customers表中返回某个customer的记录。这个方法内的代码,除了ExecuteAndSend()方法外,你应该都已经比较熟悉了。 ExecuteAndSend()方法接收一个SqlCommand对象作为参数,执行它就会返回数据集给客户端。

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


我来说两句:

1分 2分 3分 4分 5分
姓名: *


* 请各位网友遵纪守法并注意语言文明。
网站简介 | 联系方式 | 意见建议 | 版权说明
Copyright © 2007 All rights reserved
滇ICP备06006992号