0

I have seen some examples how to use parameters to avoid character escaping. Does using parameters is 100% safe against SQL injection?

Also, can you please give some basic queries (which are reguraly used), and how you implement the parameters?

Some websites I searched before I came here provided too complicated examples.

1
  • I hesitate to state that anything is 100% safe. Also, what do you mean by regularly used queries? It's entirely dependent on your data model. Commented Apr 22, 2012 at 17:04

2 Answers 2

2

A basic example of a parameterized SQL query is as follows:

SqlCommand command = new SqlCommand(@"select city from users where username = @username", conn);
SqlParameter param = new SqlParameter();
param.ParameterName = "@username";
param.Value = "abc123"
command.Parameters.Add(param);

conn is the SqlConnection that you've established.

@username is the parameter name that will be substituted when the command is executed.

abc123 is the made up username that I've put for the example.

This is obviously a made up scenario, but you get the point.

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

Comments

0

As a shorter version you can use

SqlCommand command = new SqlCommand(@"select city from users where username = @username", conn);
command.Parameters.AddWithValue("@username", "value");

2 Comments

OK - but using the .AddWithValue() method basically tells ADO.NET to guess the data type used - which it does quite well, most of the time. But sometimes, it's off - quite a bit off, at times. Therefore, I would not recommend this - it's always better to explicitly define the data type and not leave this up to guesswork by the ADO.NET runtime.....
I believe there is an overload for AddWithValue that lets you pass a type.

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.