Parameterized SQL: A Crucial Defense Against SQL Injection
Database security is paramount, especially when dealing with external inputs from web or desktop applications. Parameterized SQL statements are a cornerstone of robust database interaction, effectively preventing SQL injection attacks.
Consider a vulnerable SQL query:
<code class="language-sql">SELECT empSalary FROM employee WHERE salary = txtSalary.Text</code>
A malicious user could input 0 OR 1=1
, retrieving all salaries. Even more dangerous, input like 0; DROP TABLE employee
could lead to data loss.
Parameterized queries offer a solution. They use placeholders for user-supplied data, isolating the input from the SQL command itself.
Here's how it works in C#:
<code class="language-csharp">string sql = "SELECT empSalary FROM employee WHERE salary = @salary"; using (SqlConnection connection = new SqlConnection(/* connection info */)) using (SqlCommand command = new SqlCommand(sql, connection)) { SqlParameter salaryParam = new SqlParameter("salary", SqlDbType.Money); salaryParam.Value = txtMoney.Text; command.Parameters.Add(salaryParam); SqlDataReader results = command.ExecuteReader(); }</code>
And in Visual Basic .NET:
<code class="language-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</code>
The key is that the database treats @salary
as a data value, not as executable code. This prevents malicious code from being interpreted as SQL commands. Using parameterized queries significantly strengthens database security, mitigating the risk of data breaches and system compromise.
The above is the detailed content of How Can Parameterized SQL Statements Prevent SQL Injection Attacks?. For more information, please follow other related articles on the PHP Chinese website!