存储过程
存储过程是一组予编译的SQL语句它的优点:1.允许模块化程序设计,就是说只需要创建一次过程,以后在程序中就可以调用该过程任意次。 2.允许更快执行,如果某操作需要执行大量SQL语句或重
复执行,存储过程比SQL语句执行的要快。 3.减少网络流量,例如一个需要数百行的SQL代码的操作有一条执行语句完成,不需要在网络中发送数百行代码。 4.更好的安全机制,对于没
有权限执行存储过程的用户,也可授权他们执行存储过程。
1.不带参数的存储过程
//连接字符串
string str = @"Data Source=PC-20140331BMRR\SQLEXPRESS;Initial Catalog=lianxi;Integrated Security=True";
//创建连接对象cn
SqlConnection cn = new SqlConnection(str);
//创建执行命令的对象
SqlCommand cm = new SqlCommand();
//建立连接
cm.Connection = cn;
//要执行的存储过程的名字
cm.CommandText = "getall";
//指定要执行的是存储过程
cm.CommandType = CommandType.StoredProcedure;
SqlDataAdapter dr = new SqlDataAdapter(cm);
DataTable da = new DataTable();
dr.Fill(da);
GridView1.DataSource = da;
GridView1.DataBind();
2.带参数的存储过程
create proc byid
(@Id int)
as
select * from zy where id=@id
string str = @"Data Source=PC-20140331BMRR\SQLEXPRESS;Initial Catalog=lianxi;Integrated Security=True";
//创建连接对象cn
SqlConnection cn = new SqlConnection(str);
//创建执行命令的对象
SqlCommand cm = new SqlCommand(“存储过程的名字”,cn);
//指定执行的是存储过程
cm.CommandType = CommandType.StoredProcedure;
//传递存储过程的参数 @id
SqlParameter p = cm.Parameters.Add("@id",SqlDbType.Int);
//p的取值
p.Direction = ParameterDirection.Input;//说明参数的类型
p.Value = Convert.ToInt32(TextBox1.Text);
SqlDataAdapter dr = new SqlDataAdapter(cm);
DataTable da = new DataTable();
dr.Fill(da);
GridView1.DataSource = da;
GridView1.DataBind();