This article describes a method for using stored procedures in asp.net 2.0.
The following are two stored procedures in sql:
以下是引用片段:
CREATE PROCEDURE dbo.oa_selectalluser
AS
select * from UserInfo
GO
CREATE PROCEDURE dbo.oa_SelectByID
@id int
AS
select * from UserInfo where ID=@id
GO
One is a stored procedure with parameters, and one is a stored procedure without parameters. The following describes how to use both stored procedures in VS2005.
(i). Stored procedures with no parameters:
以下是引用片段:
protected void Page_Load(object sender, EventArgs e)
...{
if(!Page.IsPostBack)
...{
//不带参数的存储过程的使用方法
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["oaConnectionString"].ToString());
SqlDataAdapter da = new SqlDataAdapter();
DataSet ds=new DataSet();
da.SelectCommand = new SqlCommand();
da.SelectCommand.Connection = conn;
da.SelectCommand.CommandText = "oa_SelectAllUser";
da.SelectCommand.CommandType = CommandType.StoredProcedure;
da.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
}
Added a GridView control to the page to bind to the result of executing the stored procedure.
(ii). Stored Procedures with parameters:
以下是引用片段:
protected void btn_search_Click(object sender, EventArgs e)
...{
//带参数的存储过程的使用方法
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["oaConnectionString"].ToString());
SqlDataAdapter da = new SqlDataAdapter();
DataSet ds = new DataSet();
da.SelectCommand = new SqlCommand();
da.SelectCommand.Connection = conn;
da.SelectCommand.CommandText = "oa_SelectByID";
da.SelectCommand.CommandType = CommandType.StoredProcedure;
SqlParameter param = new SqlParameter("@id", SqlDbType.Int);
param.Direction = ParameterDirection.Input;
param.Value = Convert.ToInt32(txt_value.Text);
da.SelectCommand.Parameters.Add(param);
da.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
}
Similarly, a GridView control was added to the page to bind the result of executing the stored procedure, and a TextBox control and a button buttons were added to the page. The execution stored procedure above is placed in the button's OnClick event. A TextBox control is used to receive parameters from a stored procedure.