使用参数有助于防止SQL注入攻击当数据库与桌面程序或网站等程序界面结合使用时。
在您的示例中,用户可以通过在中编写语句来直接在数据库上运行 SQL 代码txtSalary
.
例如,如果他们要写0 OR 1=1
,执行的 SQL 将是
SELECT empSalary from employee where salary = 0 or 1=1
由此,所有雇员工资将被退还。
此外,用户可以对您的数据库执行更糟糕的命令,包括删除它,如果他们写0; Drop Table employee
:
SELECT empSalary from employee where salary = 0; Drop Table employee
桌子employee
然后将被删除。
就您而言,您似乎正在使用 .NET。使用参数非常简单:
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
2016年4月25日编辑:
根据 George Stocker 的评论,我将示例代码更改为不使用AddWithValue
。另外,一般建议您包裹IDisposable
s in using
声明。