sqlsql-serversql-injection

Why do we always prefer using parameters in SQL statements?


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.


Solution

  • 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 be

     SELECT empSalary from employee where salary = 0 or 1=1
    

    whereby 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:

    SELECT empSalary from employee where salary = 0; Drop Table employee
    

    The table employee would then be deleted.


    In your case, it looks like you're using .NET. Using parameters is as easy as:

    string sql = "SELECT empSalary from employee where salary = @salary";
    
    using (SqlConnection connection = new SqlConnection(/* connection info */))
    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();
    }
    
    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:

    As per George Stocker's comment, I changed the sample code to not use AddWithValue. Also, it is generally recommended that you wrap IDisposables in using statements.