登录防止sql注入的方法:
1.登录查询语句最好不要用连接字符串查询,防止sql注入1‘or’1‘=’1,代码如下:
string username="admin";
string password="123";
string str="连接字符串";
using(sqlconnection cnn=newsqlconnection(str))
{
using(sqlcommand cmd=cnn.createcommand())
{
cmd.commandtext="select count(*) from login where username='"+username+"'and password='"+password+"'";
int i=convert.toint32(cmd.executescalar());
if(i>3)
{
console.write("yes");
}
else
{
console.write("no");
}
}
}
2.登录查询语句最好要用,连接字符串来防止sql注入,例如:
string username="admin";
string password="123";
string str="连接字符串";
using(sqlconnection cnn=newsqlconnection(str))
{
using(sqlcommand cmd=cnn.createcommand())
{
cmd.commandtext="select count(*) from login where username=@username and password=@password";
cmd.parameters.add(new sqlparameter("username",username));
cmd.parameters.add(new sqlparameter("password",password));
int i=convert.toint32(cmd.executescalar());
if(i>3)
{
console.write("yes");
}
else
{
console.write("no");
}
}
}
3.限制错误登录次数,例如:
private void incerrortimes()
{
using(sqlconnection cnn2=newsqlconnection(str))
{
using(sqlcommand cmd2=cnn2.createcommand())
{
cmd2.commandtext="update login set errortimes=errortimes+1 where username=@username";
cmd2.parameters.add(new sqlparameter("username",username));
cmd2.executenonquery();
}
}
}
private void reseterrortimes()
{
using(sqlconnection cnn2=newsqlconnection(str))
{
using(sqlcommand cmd2=cnn2.createcommand())
{
cmd2.commandtext="update login set errortimes=0 where username=@username";
cmd2.parameters.add(new sqlparameter("username",username));
cmd2.executenonquery();
}
}
}
using(sqlconnection cnn=newsqlconnection(str))
{
using(sqlcommand cmd=cnn.createcommand())
{
cmd.commandtext="select * from login where username=@username";
cmd.parameters.add(new sqlparameter("username",username));
using(sqldatareader reader=cmd.executereader())
{
if(reader.read())
{
int errortimes=convert.toint32(read["errortimes"]);
if(errortimes>3)
{
console.write("登录错误次数过多,禁止登录");
return;
}
string dbpassword=read["password"];
if(password=dbpassword)
{
console.write("登录成功");
reseterrortimes()
}
else
{
console.write("登录失败");
incerrortimes();
}
}
else
{
console.write("用户名不存在");
}
}
}
}