数据库
首页 > 数据库> > 解决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";
}

标签:string,cmd,SqlConnection,SQL,解决,new,SqlParameter,conn,注入
来源: https://www.cnblogs.com/qingkongcl/p/15563684.html