在asp.net中使用sql server存储过程 (包括SqlDataAdapter调用存储过程)

数据库名称:company,

表名:company.dbo.department

 

存储过程的定义:

//获取所有department信息 create proc getalldep as select * from company.dbo.department //插入一个department create proc insertdep @ID int output, @Name varchar(50) as insert into company.dbo.department (Name) values(@Name); set @ID=@@IDENTITY

 

下面是在asp.net中使用,新建一个类 ,比如department.cs

using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Data.SqlClient; using System.Data; namespace WebApplication7 { public class department { private string constring; public Emp() { constring = "Data Source=localhost;Initial Catalog=company;user id=tt;password=y357395775@;"; } public Emp(string connectionstring) { constring = connectionstring; } public int insertemp(string name) { SqlConnection con = new SqlConnection(constring); SqlCommand cmd = new SqlCommand("insertdep", con); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.Add(new SqlParameter("@Name", SqlDbType.VarChar, 50)); cmd.Parameters["@Name"].Value = name; cmd.Parameters.Add(new SqlParameter("@ID", SqlDbType.Int)); cmd.Parameters["@ID"].Direction = ParameterDirection.Output; try { con.Open(); cmd.ExecuteNonQuery(); return (int)cmd.Parameters["@ID"].Value; } catch (SqlException exc) { Console.Write(exc.Message.ToString()); } finally { con.Close(); } } public DataTable getalldep() { SqlConnection con = new SqlConnection(constring); SqlCommand cmd = new SqlCommand("getalldep", con); cmd.CommandType = CommandType.StoredProcedure; DataSet ds=new DataSet(); SqlDataAdapter da=new SqlDataAdapter(); da.SelectCommand = cmd; da.Fill(ds, "dep"); return ds.Tables["dep"]; } } }

然后在页面上新建一个gridview控件引用之

protected void Page_Load(object sender, EventArgs e) { department dep = new department(); gvdep.DataSource = dep.getalldep(); gvdep.DataBind(); } //gridview控件的id为gvdep

这里只是实现了getalldep的使用.

 

需要注意的是SqlDataAdapter类对存储过程的调用过程:

SqlConnection con = new SqlConnection(constring); SqlCommand cmd = new SqlCommand("getalldep", con); cmd.CommandType = CommandType.StoredProcedure; DataSet ds=new DataSet(); SqlDataAdapter da=new SqlDataAdapter(); da.SelectCommand = cmd; da.Fill(ds, "dep"); return ds.Tables["dep"];

转载于:https://www.cnblogs.com/damoyan/archive/2010/05/18/2185899.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值