当数据库与程序界面(如桌面程序或网站)结合使用时,使用参数有助于防止SQL Injection attacks.
在您的示例中,用户可以通过在txtSalary
中创建语句,直接在数据库上运行SQL代码.
例如,如果他们写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
.
在你的情况下,看起来你正在使用.网使用参数非常简单:
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的 comments ,我将示例代码更改为不使用AddWithValue
.此外,一般建议您将IDisposable
个语句包装在using
个语句中.