I been reading a bit about SQL injection and I want to be sure my code is lets say "safe" from it, I was planning on using RegExp validators to check the user input but another post in here suggested only using parametrized querys, well I'm using them but I want to be sure my code is safe, is it?
using ( SqlConnection dataConnection = new SqlConnection(myConnectionString) )
{
using ( SqlCommand dataCommand = dataConnection.CreateCommand() )
{
dataCommand.CommandText = "INSERT INTO Lines (Name, CreationTime) " +
"VALUES (@LineName, @CurrentDateTime)";
dataCommand.Parameters.AddWithValue("@LineName", TextBox2.Text);
dataCommand.Parameters.AddWithValue("@CurrentDateTime", DateTime.Now.ToString());
dataConnection.Open();
//do other DB stuff
I chop the last part to make the post shorter, the rest is just trying and catching exceptions and closing db connection as well as providing user feedback on inserting successful.
The only sure way to prevent SQL Injection attacks is input validation and parametrized queries including prepared statements.
Stored procedures only directly prevent SQL injection if you call them in a paramerized way. If you still have a string in your app with the procedure name and concatenate parameters from user input to that string in your code you'll have still have trouble.
SQL injection (SQLi) is a web security vulnerability that allows an attacker to interfere with the queries that an application makes to its database. It generally allows an attacker to view data that they are not normally able to retrieve.
Your code is fine, it is protected from injection because the values are passed as parameters not string literals. However, if you are writing this type of data access yourself, have you considered creating SqlParameter objects and explicitly setting the type, size etc, and adding the parameters to the command? AddWithValue will work just fine, but SQL Server will have to determine the type, a little, but unnecessary overhead.
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