I recently notice a lot of "Why doesn't my SQL statement work?" questions, where the cause of the problem is some improperly formatted (date) or improperly escaped (string) value.
Of course, we all know that the real problem is that the OP uses string concatenation to paste user-supplied values into his SQL instead of using parameters, which are not only safer, but also avoid all escaping/formatting issues.
Hence, I'd like to use my dupe hammer to link those questions to some great question explaining generally and in easy terms how to use SQL parameters in C# with SQL Server.
Unfortunately, I have not found such a great question yet - most good, tutorial-like explanations on this subject are off-site. Yes, there are a lot of duplicates, but most are about one very specific issue with a lot of noise, and, thus, not a good dupe target.
Is there a good canonical question for this issue or should I write one?
Paramaters.Add()
as the preferred method rather thanAddWithValue()
which as you say can cause some quite subtle issues.Add
introduces additional redundancy and is not needed in most of the cases (especially if you already use nvarchars, as is good practice anyway). Personally, I'm in the "use AddWithValue when possible and Add when necessary" camp. I'll see if I can make theAdd
note more prominent.