登录方法及防止sql注入

登录查询语句最好不要用连接字符串查询,防止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");
  }
 }
}

登录查询语句最好要用,防止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");
  }
 }
}

限制错误登录次数
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("用户名不存在");
      }
    }
  }
}

你可能感兴趣的:(登录方法及防止sql注入)