I am very new to working with databases. Now I can write SELECT, UPDATE, DELETE, and INSERT commands. But I have seen many forums where we prefer to write:
SELECT empSalary from employee where salary = @salary
…instead of:
SELECT empSalary from employee where salary = txtSalary.Text
Why do we always prefer to use parameters and how would I use them?
I wanted to know the use and benefits of the first method. I have even heard of SQL injection but I don’t fully understand it. I don’t even know if SQL injection is related to my question.
Using parameters helps prevent SQL Injection attacks when the database is used in conjunction with a program interface such as a desktop program or web site.
In your example, a user can directly run SQL code on your database by crafting statements in
txtSalary.For example, if they were to write
0 OR 1=1, the executed SQL would bewhereby all empSalaries would be returned.
Further, a user could perform far worse commands against your database, including deleting it If they wrote
0; Drop Table employee:The table
employeewould then be deleted.In your case, it looks like you’re using .NET. Using parameters is as easy as:
Edit 2016-4-25:
As per George Stocker’s comment, I changed the sample code to not use
AddWithValue. Also, it is generally recommended that you wrapIDisposables inusingstatements.