-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 + "'";
codeBoy
  • 533
  • 3
  • 7
  • 23

1 Answers1

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);
Ben
  • 2,433
  • 5
  • 39
  • 69
  • Ben, with this i get "Must declare the scalar variable" for username. I am using the "or like this" option – codeBoy Jun 03 '15 at 18:57