项目中存储过程的一个C#例子,一个展示页面需要显示不同表(申请动态,相关资料,资料下载等)的信息;因为逻辑功能都一样,sql语句都是select top(6) * from table;只是表面不同,逻辑功能一样,就可以模仿面向对象语言的对象的方法模式,把查询功能封装一个存储过程(方法),表明做参数。
这样使用使用存储过程不仅使对数据库访问操作更便捷,而且更安全,不易遭受sql注入攻击。
下面是项目中的一个名为 sp_review_releaseInfo 的存储过程,代码如下:
ALTER PROCEDURE [dbo].[sp_review_releaseInfo]
@type varchar(50),
@other varchar(200)
AS
BEGIN
if(@type='release_dongtai')
begin
select top(6) info_title,info_id,release_date from review_releaseInfo where release_id='1' and is_state='启用'
order by release_date desc
end
if(@type='release_cailiao')
begin
select top(6) info_title,info_id,release_date from review_releaseInfo where release_id='2' and is_state='启用'
order by release_date desc
end
if(@type='release_upload')
begin
select top(6) true_name,info_id,file_url from View_relsase_upload where is_state='启用'
order by release_date desc
end
if(@type='release_upload_list')
begin
select info_title, true_name,filel_id,file_url,[file_name] from View_relsase_upload where info_id=@other
order by release_date desc
end
if(@type='release_list')
begin
SELECT review_releaseInfo.info_id,review_releaseInfo.info_title,review_releaseInfo.is_state,
review_releaseInfo.person_name,review_releaseInfo.release_date,review_releaseType.release_name
FROM review_releaseInfo INNER JOIN review_releaseType ON review_releaseInfo.release_id = review_releaseType.release_id
order by release_date desc
end
END
C#端的调用存储过程的代码,如下
protected void Bind_data() {//调用bind_data()函数,传入不同栏目的参数 this.GridView1.DataKeyNames = new string[] { "info_id" }; GridView1.DataSource = bind_data("release_dongtai"); GridView1.DataBind(); this.GridView2.DataKeyNames = new string[] { "info_id" }; GridView2.DataSource = bind_data("release_cailiao"); GridView2.DataBind(); this.GridView3.DataKeyNames = new string[] { "info_id" }; GridView3.DataSource = bind_data("release_upload"); GridView3.DataBind(); } protected DataSet bind_data(string type) {//根据栏目参数type,利用存储过程查询数据库,最后返回展示不同表的查询信息 Con = new SqlConnection(ConnStr); if (Con.State != ConnectionState.Open) { Con.Open(); } ds.Clear(); cmd = new SqlCommand("[sp_review_releaseInfo]", Con); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@type", type); cmd.Parameters.AddWithValue("@other", ""); cmd.ExecuteNonQuery(); da.SelectCommand = cmd; if (ds != null) { da.Fill(ds, "table"); } Con.Close(); return ds; }