Your approach is wrong from the very beginning. The query composed by concatenation with strings taken from UI. Not only repeated string concatenation is inefficient (because strings are
immutable; do I have to explain why it makes repeated concatenation bad?), but there is way more important issue: it opens the doors to a well-known exploit called
SQL injection. Richard Deeming made it clear in his comment to the question, but you may need some explanations.
This is how it works:
http://xkcd.com/327.
Are you getting the idea? The string taken from a control can be anything, including… a fragment of SQL code.
What to do? Just read about this problem and the main remedy:
parametrized statements:
http://en.wikipedia.org/wiki/SQL_injection.
With ADO.NET, use this:
http://msdn.microsoft.com/en-us/library/ff648339.aspx.
Please see my past answers for some more detail:
EROR IN UPATE in com.ExecuteNonQuery();,
hi name is not displaying in name?.
It has nothing to do with validation; neither your code does. If you need validation, just do it
before using your SQL statement. Most likely, you will need validation just as as part of the procedure you have to perform to parse the text to some typed data you need to assign to a parameter of your
parameterized statement.
—SA