存储过程在应用程序端的使用的优点
1 如果sq1语句直接写在客户端,以一个字符中的形式体现的,提示不友好,会导致效率降低
2 sql语句写在客户端,可以利用sql注入进行攻击,为了安全性,可以把sql封装在服务器存储过程,在客户端进行调用即可
-- 1. 自定义无参数存储过程:
-- 创建存储过程 usp_ScoreQuery1
-- 查询考试成绩,显示:学号、姓名、班级、总成绩,并按成绩的总分高低排序。
-- 统计分析考试成绩,显示班级名称、C#平均分、数据库平均分,按照班级分组实现。
在WinForm中添加一个按钮和两个dataGridView控件,我们要在winform中调用SQL中的存储,代码如下
以上是定义两个类去接收查询出来的两个表
随后在按钮的点击事件中调用SQL中的事件
string proceName = "usp_ScoreQuery1";
SqlCommand cmd = new SqlCommand();
cmd.CommandText = proceName;
cmd.Connection = conn;
cmd.CommandType = System.Data.CommandType.StoredProcedure;
List<Modell> model1 = new List<Modell>();
List<Model2> model2 = new List<Model2>();
try
{
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
model1.Add(new Modell()
{
StudentId = Convert.ToInt32(dr["StudentId"]),
StudentName = dr["StudentName"].ToString(),
ClassName = dr["ClassName"].ToString(),
ScoreNum = Convert.ToInt32(dr["ScoreSum"])
});
}
if (dr.NextResult())
{
while (dr.Read())
{
model2.Add(new Model2()
{
ClassName = dr["ClassName"].ToString(),
CSherpAvg = Convert.ToInt32(dr["C#Avg"]),
DBAvg = Convert.ToInt32(dr["DBAvg"])
});
}
}
dr.Close();
this.dataGridView1.DataSource = model1;
this.dataGridView2.DataSource = model2;
}
catch (Exception)
{
throw;
}