Java教程

解决SQL注入问题

本文主要是介绍解决SQL注入问题,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

原来的代码

public string Remove(string id)
{
  using SqlConnection conn = new SqlConnection("server=.;database=dbo;uid=sa;pwd=123");
  conn.Open();
  SqlCommand cmd = new SqlCommand($"DELETE FROM Users WHERE Id = {id}",conn);
  cmd.ExecuteNonQuery();
  return "1";
}

修改后的代码

public string Remove(string id)
{
  using SqlConnection conn = new SqlConnection("server=.;database=dbo;uid=sa;pwd=123");
  conn.Open();
  
  
  SqlCommand cmd = new SqlCommand($"DELETE FROM Users WHERE Id = @Id",conn);
  
  SqlParameter sqlParameter = new SqlParameter("@Id",id);
  cmd.Parameters.Add(sqlParameter);
  
  cmd.ExecuteNonQuery();
  
  
  return "1";
}

传多个参数时

public string Remove(string userNo,string userName)
{
  using SqlConnection conn = new SqlConnection("server=.;database=dbo;uid=sa;pwd=123");
  conn.Open();
  
  
  SqlCommand cmd = new SqlCommand($"DELETE FROM Users WHERE UserNo = @UserNo AND UserName = @UserName",conn);
  
  SqlParameter sqlParameter = new SqlParameter[]{
    new SqlParameter("@UserNo",userNo),
    new SqlParameter("@UserName",userName)
  };
  cmd.Parameters.AddRange(sqlParameter);
  
  cmd.ExecuteNonQuery();
  
  
  return "1";
}
这篇关于解决SQL注入问题的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!