Using parameters helps prevent SQL Injection attacks when the database is used in conjunction with a software interface such as a desktop program or website.
In your example, the user can directly run SQL code in your database by creating instructions in txtSalary .
For example, if they were to write 0 OR 1=1 , the executable SQL would be
SELECT empSalary from employee where salary = 0 or 1=1
as a result, all empSalaries will be returned.
In addition, the user can execute much worse commands against your database, including deleting it if they wrote 0; Drop Table employee 0; Drop Table employee :
SELECT empSalary from employee where salary = 0; Drop Table employee
Then the employee table will be deleted.
In your case, it looks like you are using .NET. Using parameters is as simple as:
FROM#
string sql = "SELECT empSalary from employee where salary = @salary"; using (SqlConnection connection = new SqlConnection()) using (SqlCommand command = new SqlCommand(sql, connection)) { var salaryParam = new SqlParameter("salary", SqlDbType.Money); salaryParam.Value = txtMoney.Text; command.Parameters.Add(salaryParam); var results = command.ExecuteReader(); }
Vb.net
Dim sql As String = "SELECT empSalary from employee where salary = @salary" Using connection As New SqlConnection("connectionString") Using command As New SqlCommand(sql, connection) Dim salaryParam = New SqlParameter("salary", SqlDbType.Money) salaryParam.Value = txtMoney.Text command.Parameters.Add(salaryParam) Dim results = command.ExecuteReader() End Using End Using
Edit 2016-4-25:
According to a comment by George Stocker, I changed the code sample to not use AddWithValue . In addition, it is usually recommended to wrap IDisposable in using statements.
Chad Levy Sep 21 '11 at 19:54 2011-09-21 19:54
source share