//创建查询所有学生信息的存储过程到数据库SQL
use TestDB
go
if OBJECT_ID(‘GetStudent’,‘P’) IS Not Null
Drop Procedure GetStudent
go
Create Procedure GetStudent
AS
Select SNO, SName, Gender, Birthday, Mobile, Email, HomeAddress, PhotoPath from Student
GO
//查询所有学生信息的存储过程的调用的方法
private void LoadAllStudentInfo()
{
//实例化DataSet
DataSet ds = new DataSet();
//实例化conn
SqlConnection conn = new SqlConnection(connString);
//实例化cmd
SqlCommand cmd = new SqlCommand();
//指定使用的链接对象
cmd.Connection = conn;
//指定使用的类型来存储过程
cmd.CommandType = CommandType.StoredProcedure;
//指定存储过程的名称
cmd.CommandText = “GetStudent”;//数据库中的存储过程
//执行并接收返回值
try
{//打开
conn.Open();
//实例化dayaReader的对象
SqlDataReader sdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
ds.Tables.Add(“Student”);
ds.Tables[“Student”].Load(sdr);
//展示数据
dgvStudent.DataSource = ds.Tables[“Student”];
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
//带有参数的存储过程创建
use TestDB
go
if OBJECT_ID(‘GetStudent’,‘P’) IS Not Null
Drop Procedure GetStudent
go
Create Procedure GetStudent
@SNO int
AS
Select SNO, SName, Gender, Birthday, Mobile, Email, HomeAddress, PhotoPath from Student where SNO=@SNO
GO
//调用带有参数的存储过程
private void LoadAllStudentInfo()
{
//实例化DataSet
DataSet ds = new DataSet();
//实例化conn
SqlConnection conn = new SqlConnection(connString);
//实例化cmd
SqlCommand cmd = new SqlCommand();
//指定使用的链接对象
cmd.Connection = conn;
//指定使用的类型来存储过程
cmd.CommandType = CommandType.StoredProcedure;
//指定存储过程的名称
cmd.CommandText = “GetStudent”;//数据库中的存储过程
//指定查询的参数数组
SqlParameter[] prar = new SqlParameter[]
{
new SqlParameter("@SNO",“95002”),
};
//执行并接收返回值
try
{//打开
conn.Open();
//调用存储过程中的参数
cmd.Parameters.AddRange(prar);
//实例化dayaReader的对象
SqlDataReader sdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
ds.Tables.Add(“Student”);
ds.Tables[“Student”].Load(sdr);
//展示数据
dgvStudent.DataSource = ds.Tables[“Student”];
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}