1. 参数化命令相关知识点:(防止SQL注入)
DAL类:
public DataTable StudentDAL(string name,string gender)
{
string str="连接字符串";
using (SqlConnection con=new SqlConnection(str))
{
string sql="select * from student where studentName=@name and Gender=@gender";
SqlCommand cmd=new SqlCommand();
SqlParameter [] para=
{
new SqlParameter=("@name",name)
new SqlParameter=("@gender",gender)
};
cmd .Parameter.AddRange(para);
SqlDataadapter da=new SqlDataadapter(cmd);
DataSet dt=new DataSet();
da.Fill();
return.Table[0];
}
}
}
2. 在C#中调用存储过程:
--创建存储过程:
create proc usp_selectStudent
@studentName nvarchar(50)
as
select * from Student where StudentName=@studentName
GO
--DAL类:
public DataTable GetStudentInfo(string name)
{
string str="连接字符串";
using (SqlConnection con =new SqlConnection(str))
{
string sql="usp_selectStudent";
SqlDataadapter da=new SqlDataadapter(sql,con);
SqlCommand com=da .selectcommand;
//指定字符串为存储过程
com.CommandType=CommandType.StoredProcedure;
SqlParameter para=new SqlParameter("@name",name);
com.parameter.Add(para);
DataSet dt=new DataSet();
da.Fill();
return dt.Table[0];
}
}
3. 在C#中调用带输出参数的存储过程:
--创建存储过程:
create pro usp_selectStudentCount
@name nvarchar(50)
@Gender nvarchar(50) output
as
select @Gender=count(*) from student where studentName=@name
select * from Student where StudentName=@name
GO
DAL类:
public DataTable GetStudentCount(string name,string Gender)
{
string str="连接字符串";
using(SqlConnection con=new SqlConnection)
{
string usp_selectStudentCount
SqlDataadapter da=new SqlDataadapter(sql,con);
SqlCommand com=da.selectcommand;
com.CommandType=CommandType.StoredProcedure;
SqlParameter [] para=
{
new SqlParameter("@name",name);
//设置为输出参数
new SqlParameter("@gender",gender);
}
//设置最后一个参数的输出方向
para[para.Legth-1].Direction=ParameterDiraction.output;
com.parameter.AddRange(para);
DataSet dt=new DataSet();
da.Fill(dt);
return Table dt.Table[0];
}
}
多余:
1: SQL语句通过字符串的构造技术动态创建,文本框的值被直接复制到字符串,
string sql="select * from Orders where CustomerID='"+txtID.Text+"'";
2: string sql="select * from Orders where CustomerID='ALFKI' or '1'='1'";
3: 删除Customers表中的全部行
"select * from Orders where CustomerID='ALFKI';delete * from Customers";
存储过程的优点:
:易于维护
: 更安全的使用数据库
:提升性能
参数化命令(防止SQL注入)
最新推荐文章于 2024-06-25 09:29:55 发布