-3

This is a simple query I have written. What would be the best way to paramaterize this to prevent SQL injection?

string selectQuery = "select [ID] from [myDB].[dbo].[myTable] where [myName] = '" +  user.globalUserName + "'";
0

1 Answer 1

3

You can use the @ to define a parameter, like this:

string selectQuery = "select [ID] from [myDB].[dbo].[myTable] where [myName] = @username;";

Then you can define the parameter by using the Command.Parameters Function, like this:

cmd.Parameters.Add("@username", SqlDbType.VarChar);
cmd.Parameters["@username"].Value = user.globalusername;

or like this:

cmd.Parameters.AddWithValue("@Username", user.globalusername);
Sign up to request clarification or add additional context in comments.

1 Comment

Ben, with this i get "Must declare the scalar variable" for username. I am using the "or like this" option

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.