What is the advantage of using parameters over using string interpolation?
Is this
SELECT * FROM dbo.Posts WHERE Author = @p0", userSuppliedAuthor;
any better than
$@SELECT * FROM dbo.Posts WHERE Author = {userSuppliedAuthor}";
?
When an interpolated string is resolved to a result string, items with interpolation expressions are replaced by the string representations of the expression results. This feature is available starting with C# 6. String interpolation provides a more readable, convenient syntax to format strings. It's easier to read than string composite formatting.
There’s no compile-time relationship between a format string and its arguments. String interpolation improves on that, so we’re taking advantage of it. We’re declaring the intent of our code as explicitly as possible so that future developers can easily understand what they’re about to modify.
C# language specification. See also. The $ special character identifies a string literal as an interpolated string. An interpolated string is a string literal that might contain interpolation expressions. When an interpolated string is resolved to a result string, items with interpolation expressions are replaced by the string representations ...
When an interpolated string is resolved to a result string, items with interpolation expressions are replaced by the string representations of the expression results. This feature is available starting with C# 6.
String interpolation is just a syntax sugar for formatting string. It gives you no protection against SQL injection. You should use SQL parameters to provide values for your query.
Consider - what if userSuppliedAuthor
equals to
'Bob' OR 1 = 1
Or even
'Bob'; DROP TABLE Users;
Further reading SQL Injection
In addition to SQL injection issues mentioned by Sergey, you can have issues with totally valid strings that contain certain characters, like "'", "." and "@" characters that mean things to SQL and need to be handled. It's always best to parameterize queries to prevent these issues, not only with injection when going straight from user input, but even something as simple as an email address or a possessive in a title.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With