0

as per question once more: Do we really need to pass numbers datatype variable values as parameters to prevent sql injection.

I do have two sample function one with parameter and next without using parameter

function CheckThis(int UIN)
{
  var connect = ConfigurationManager.ConnectionStrings["NorthWind"].ToString();
  var query = "Select * From Products Where ProductID = @ProductID";
  using (var conn = new SqlConnection(connect))
  {
    using (var cmd = new SqlCommand(query, conn))
    {
      cmd.Parameters.Add("@ProductID", SqlDbType.Int);
      cmd.Parameters["@ProductID"].Value = UIN;
      conn.Open();
      //Process results
    }
  }
}

OR is following ok

function CheckThis(int UIN)
{
  var connect = ConfigurationManager.ConnectionStrings["NorthWind"].ToString();
  var query = "Select * From Products Where ProductID = " + UIN;
  using (var conn = new SqlConnection(connect))
  {
    using (var cmd = new SqlCommand(query, conn))
    {
      //cmd.Parameters.Add("@ProductID", SqlDbType.Int);
      //cmd.Parameters["@ProductID"].Value = UIN;
      conn.Open();
      //Process results
    }
  }
}

1 Answer 1

4

You don't need to do it to stop SQL injection attacks1. However:

  • Your code is cleaner if you separate the SQL from the values
  • If the type is later changed from int to something else, you would then be at risk of an injection attack, and it's entirely possible that it would be missed in code review
  • It avoids any issues with number-to-string conversions involving unexpected thousands separators etc

In short, I would definitely still use parameters.


1 Unless your attacker can also affect your locale settings. At that point, even string concatenation with integers can be vulnerable to SQL injection attacks.

Sign up to request clarification or add additional context in comments.

8 Comments

gr8... listing of advantages of using it
I wonder if it's the same for decimal, bignum, and floating-point types?
@Panzercrisis: Yes, absolutely. Parameterization is simply the way to go.
Are they able to be hacked?
@Panzercrisis: Ah. They're mostly as safe as integer types, unless someone can change your culture settings (in which case you're in trouble) but they're more likely to suffer from conversion issues.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.