7*24小时应急电话:15927160396
首页 新闻资讯 技术文章
C# 调用sql 2000存储过程
调用带输参数的存储过程

     首先自然是在查询分析器里创建一个存储过程喽~~   如下所示:
create proc proc_1
@uid int
,
@pwd varchar(255
)
as

select UserName from users where uid = @uid and PassWord = @pwd
go
 

     接下来我们就来看下如何在VS 2005中使用C#调用这个存储过程。

     方法一:


Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

-->SqlConnection conn = new SqlConnection("server=(local);database=sql1;uid=sa;pwd=");
conn.Open();
//打开数据库连接
SqlCommand cmd = new SqlCommand("exec proc_1 @uid=1,@pwd=admin", conn);//Command中写调用存储过程的语句
//大家应该看出来了和直接在查询分析器中执行很类似,“exec 存储过程名 @参数1=参数值,@参数2=参数值”
SqlDataReader sdr = cmd.ExecuteReader();//执行存储过程
while (sdr.Read())
{
    Response.Write(sdr[
"UserName"].ToString());//输出查询到的值
}
sdr.Close();
conn.Close();

     方法二:


Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

-->SqlConnection conn = new SqlConnection("server=(local);database=sql1;uid=sa;pwd=");
conn.Open();
//打开数据库连接
SqlCommand cmd = new SqlCommand("proc_1", conn);//存储过程名
cmd.CommandType = CommandType.StoredProcedure;//设置命令类型为存储过程
SqlParameter[] param = new SqlParameter[]{
   
new SqlParameter("uid", SqlDbType.Int, 4),
   
new SqlParameter("pwd", SqlDbType.VarChar,255), 
};
//定义参数,这些是存储过程中要调用的参数,也可以通过直接使用cmd.AddWithValue方法添加参数
param[0].Value = 1;//给参数赋值
param[1].Value = "admin";
cmd.Parameters.AddRange(param);
//一定要记得将刚定义的参数添加到cmd的参数中,不然前面的参数就白弄了。
string sname =(string)cmd.ExecuteScalar();//如果存储过程返回的是单个值,我们可以直接这样取出所要的值
Response.Write(sname);
sdr.Close();
conn.Close();

 

     调用带输参数的存储过程

     上面所讲的只是调用输入参数的存储过程,下面大概讲一下如何调用有输出参数的存储过程。

     首先,我们先对之前的存储过程修改一下,如下所示:


Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

-->create proc proc_1
@uid int,
@pwd varchar(255),
@UserName varchar(255) output --这里我们增加一个输出变量,记得加上output
as
select @UserName=UserName from users where uid = @uid and PassWord = @pwd
go

--以下是在查询分析器中调用的方法
declare @n varchar(255--声明一个变量用来传递参数
exec proc_1 1,admin,@n output --注,要标记为output变量
print @n

     下面我们看看在VS.NET 中的调用方式:


Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

-->SqlConnection conn = new SqlConnection("server=(local);database=sql1;uid=sa;pwd=");
conn.Open();
SqlCommand cmd 
= new SqlCommand("proc_1", conn);
cmd.CommandType 
= CommandType.StoredProcedure;
cmd.Parameters.AddWithValue(
"uid"1);
cmd.Parameters.AddWithValue(
"pwd""admin");
cmd.Parameters.Add(
"username", SqlDbType.VarChar, 255);
cmd.Parameters[
"username"].Direction = ParameterDirection.Output;//设置参数为输出参数
cmd.ExecuteNonQuery();
string sname = (string)cmd.Parameters["username"].Value;//获取输出参数的值
Response.Write(sname);
conn.Close();
版权所有:武汉网福互联科技有限公司    鄂ICP备09022096号
业务QQ:23444550 客服QQ:267052100 电邮:23444550@qq.com  

鄂公网安备 42010602000905号

手机站二维码