参数化命令相关知识点(防止Sql注入)
一: 使用参数化命令查询
DAL类:
public DataTable StudentDAL(string name,string gender)
{
string str="连接字符串";
using(sqlconnection con=new sqlconnection(str))
{
string sql="select * from stdent where studentName=@name and Gender=@gender";
sqlcommand com=new sqlcommand();
sqlparameter[] par=
{
new sqlparameter=("@name",name),
new sqlparameter=("@gender",gender);
};
com.parameters.addRange(par);
sqldataadapter da=new sqldataadapter(com);
dataset dt=new dataset();
da.Fill(dt);
return dt.Tables[0];
}
}
二:在C#中调用带输入参数的存储过程
--创建存储过程
create proc usp_selectStudent
@studentName nvarchar(10)
as
select * froom student where StudentName=@studentNanme
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 par=new sqlparameter=("@name",name);
com.parameter.add(par);
dataset dt=new dataset();
da.Fill(dt);
return dt.Tables[0];
}
}
三: 在C#中调用带输出参数的存储过程
--创建存储过程
create proc usp_selectstudentCount
@name nvarchar(10)
@Gender nvarchar(10) output
as
select @Gender=count(*) from student where studentName=@name;
select * froom student where studentName=@name;
go
DAL类
public DataTable GetStudentCount(string name,string Gender)
{
string str="连接字符串";
using(sqlconnection con=new sqlconnection(str))
{
string usp_selectstudentCount
sqldataadapter da=new sqldataadapter(sql,con);
sqlcommand com=da.selectCommand;
com.CommandType=CommandType.StoredProcedure;
sqlparameter [] pa=
{
new sqlparameter("@name",name),
//设置为输出参数
new sqlparameter("@Gender",sqlDbType.nvarchar,10)
}
//设置最后一个参数的输出 方向
pa[pa.length-1].Direction=ParameterDiraction.OutPut;
com.parameter.addRange(pa);
string count=pa[pa.length-1].value.toString();
dataset dt=new dataset();
da.Fill(dt);
return Table dt.Table[0];
}
}