技术开发 频道

JSP、ASP.NET和存储过程

  二、在asp.net(C#)中,使用存储过程:

  1  C#中存储过程的使用标准版   

private void sql_proc()
  {  
   SqlConnection conn
=new SqlConnection("server=.;uid=sa;pwd=1234;database=china");
  
string sql="proc_out";
   SqlCommand comm
=new SqlCommand(sql,conn);
  
  
//把Command执行类型改为存储过程方式,默认为Text。
   comm.CommandType=CommandType.StoredProcedure;
  
//传递一个输入参数,需赋值
   SqlParameter sp=comm.Parameters.Add("@uid",SqlDbType.Int);
   sp.Value
=10;
  
//定义一个输出参数,不需赋值。Direction用来描述参数的类型
  
//Direction默认为输入参数,还有输出参数和返回值型。
   sp=comm.Parameters.Add("@output",SqlDbType.VarChar,50);
   sp.Direction
=ParameterDirection.Output;
  
//定义过程的返回值参数,过程执行完之后,将把过程的返回值赋值给名为myreturn的Paremeters赋值。
   sp=comm.Parameters.Add("myreturn",SqlDbType.Int);
   sp.Direction
=ParameterDirection.ReturnValue;
  
  
//使用SqlDataAdapter将自动完成数据库的打开和关闭过程,并执行相应t-sql语句或存储过程
  
//如果存储过程只是执行相关操作,如级联删除或更新,使用SqlCommand的execute方法即可。
   SqlDataAdapter da=new SqlDataAdapter(comm);
   DataSet ds
=new DataSet();
   da.Fill(ds);
  
  
  
//在执行完存储过程之后,可得到输出参数
   string myout=comm.Parameters["@output"].Value.ToString();
  
  
//打印输出参数:
   Response.Write("打印输出参数:"+myout);
  
//打印存储过程返回值
   myout=comm.Parameters["myreturn"].Value.ToString();
   Response.Write(
"存储过程返回值:"+myout);
  
this.DataGrid1.DataSource=ds;
  
this.DataGrid1.DataBind();
  
  }

 

  2 存储过程的使用最简版:  

private void sql_jyh()
  {
  
//最简写法,把存储过程当作t-sql语句来使用,语法为:exec 过程名 参数
  SqlConnection conn=new SqlConnection("server=.;uid=sa;pwd=1234;database=china");
  
string sql="execute proc_out 10,'12'";
  SqlCommand comm
=new SqlCommand(sql,conn);
  
  
//使用SqlDataAdapter将自动完成数据库的打开和关闭过程,并执行相应t-sql语句或存储过程
  
//如果存储过程只是执行相关操作,如级联删除或更新,使用SqlCommand的execute方法即可。
  SqlDataAdapter da=new SqlDataAdapter(comm);
  DataSet ds
=new DataSet();
  da.Fill(ds);
  
  
//绑定数据
  this.DataGrid1.DataSource=ds;
  
this.DataGrid1.DataBind();
  
  }

 

  总结,对于SQLServer库而言,无论用什么语言,都可以这样来使用,即当作普通查询语句。

  string sql="execute proc_out 10,'12'";

  把这个sql作为参数,在java或者C#中均能得到正确的执行。这也是使用存储过程的最简方法。

0
相关文章