登錄防止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("用戶名不存在");
}
}
}
}