When working with data, you'll often want to filter results based on some criteria. Typically, this is done by accepting input from a user and using that input to form a SQL query.
As you know, the SQL query assigned to a SqlCommand object is simply a string. So, if you want to filter a query, you could build the string dynamically, but you wouldn't want to. Here is a bad example of filtering a query.
SqlCommand cmd = new SqlCommand(
"select * from Customers where city = '" + inputCity + "'";
Don't ever build a query this way! The input variable, inputCity, is typically retrieved from a TextBox control on either a Windows form or a Web Page. Anything placed into that TextBox control will be put into inputCity and added to your SQL string. This situation invites a hacker to replace that string with something malicious. In the worst case, you could give full control of your computer away.
Using parameterized queries is a three step process:
Construct the SqlCommand command string with parameters.
Declare a SqlParameter object, assigning values as
appropriate.
Assign the SqlParameter object to the SqlCommand object's
Parameters property.
preparing a SqlCommand Object for Parameters
he first step in using parameters in SQL queries is to build a command string containing parameter placeholders. These placeholders are filled in with actual parameter values when the SqlCommand executes. Proper syntax of a parameter is to use an '@' symbol prefix on the parameter name as shown below:
SqlCommand cmd = new SqlCommand(
"select * from Customers where city = @City", conn);
Share And Enjoy:These icons link to social bookmarking sites where readers can share and discover new web pages.
Keywords:
Adding Parameters to Commands, batch file commands, batch file parameters, dos commands, windows commands, unix commands, cmd commands, batch commands