一、什么是存储过程
存储过程就是在大型数据库中,一种完成特定功能的SQL语句集
;一次编译永久有效,最后返回用户想要的结果,所以在较为复杂的业务处理中,通常使用存储过程封装查询语句。
使用SqlCommand
对象调用存储过程时与执行SQL语句命令有很大的区别,主要包含对存储过程参数的传递,输出参数获取以及存储过程返回值等本质上的区别。
二、例子:使用Command对象调用存储过程实现搜索功能
这个例子,是基于上一篇博客的内容的,上一部分博客点我前往页面!!
先来看一下效果:
然后看一下逐步的实现过程:
步骤1: 创建存储过程,首先点击School
数据库,然后打开可编程性
,右键单击存储过程
,最后单击新建
,这样:
然后写入Sql
语句:
create proc GetStudentList
@SearchValue varchar(256)=''
as
begin
if @SearchValue<>''
begin
select * from [dbo].[Student] where Name like '%'+@SearchValue+'%'
end
else
begin
select * from [dbo].[Student]
end
end
步骤2: 新建网站,创建Default.aspx
页面,在页面添加文本框和输入框控件:
<div>
<div>
<asp:TextBox ID="TextBox1" runat="server" class="TxtSearch"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="搜索" CssClass="BtnSearch" OnClick="Button1_Click" />
</div>
<div id="tabList" runat="server">
</div>
</div>
步骤3: 为表格和搜索建设置CSS
样式:
<style type="text/css">
.TxtSearch,.BtnSearch{
border-width:1px;
border-style:solid;
}
table,table th,table td{
border:1px;
border-style:solid;
border-color:#22bbad;
}
table th{
border-color:white;
}
table{
border-collapse:collapse;
}
table th{
width:150px;
height:30px;
text-align:center;
background-color:#22bbad;
color:white;
}
table td{
height:30px;
text-align:center;
}
</style>
步骤4: 为button
绑定事件处理方法,并且在页面载入时直接显示所有数据:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string Res = GetSqlData();
this.tabList.InnerHtml = Res;
}
}
protected void Button1_Click(object sender, EventArgs e)
{
string Res = GetSqlData();
this.tabList.InnerHtml = Res;
}
步骤5: 写GetSqlData
方法:
private string GetSqlData()
{
string SearchValue = this.TextBox1.Text;
StringBuilder Res = new StringBuilder();
Res.Append("<table><tr><th>序号</th><th>姓名</th><th>性别</th><th>年龄</th><th>班级</th></tr>");
using(SqlConnection conn = new SqlConnection("Server=DESKTOP-9FCSCD4;DataBase=School;Trusted_Connection=SSPI"))
{
conn.Open();
SqlCommand comm = new SqlCommand();
//指定发送到数据库的执行命令为调用存储过程
comm.CommandType = CommandType.StoredProcedure;
comm.CommandText = "GetStudentList"; //存储过程的名称
comm.Connection = conn;
//定义存储过程中的参数
SqlParameter Param = new SqlParameter("SearchValue", SqlDbType.VarChar, 256);
Param.Value = SearchValue; //设置参数值
comm.Parameters.Add(Param);
using(SqlDataReader DataReader = comm.ExecuteReader())
{
while (DataReader.Read())
{
int ID = (int)DataReader["ID"];
string Name = (string)DataReader["Name"];
string Sex = (string)DataReader["Sex"];
int Age = (int)DataReader["Age"];
string Class = (string)DataReader["Class"];
Res.Append("<tr><td>" + ID + "</td>");
Res.Append("<td>" + Name + "</td>");
Res.Append("<td>" + Sex + "</td>");
Res.Append("<td>" + Age + "</td>");
Res.Append("<td>" + Class + "</td></tr>");
}
}
comm.Dispose();
}
Res.Append("</table>");
return Res.ToString();
}
完成!