使用参数化查询
在执行SQL查询时,应该避免将直接拼接用户输入的数据到查询字符串里,因为这会导致SQL注入攻击的风险。为了避免这种情况,可以使用参数化查询。参数化查询可以将用户输入的数据视为变量,然后将变量传递给查询,而不是将纯文本数据直接拼接到查询字符串中。
下面是一个使用参数化查询的示例代码:
string connectionString = "Server=myServerAddress;Database=myDataBase;User Id=myUsername;Password=myPassword;";
string query = "SELECT * FROM customers WHERE customerID = @customerId";
using(SqlConnection connection = new SqlConnection(connectionString)) { SqlCommand command = new SqlCommand(query, connection);
command.Parameters.AddWithValue("@customerId", "ALFKI");
SqlDataAdapter adapter = new SqlDataAdapter(command);
DataSet dataSet = new DataSet();
adapter.Fill(dataSet);
}
在上面的代码中,我们创建了一个查询字符串,其中参数'@customerId”表示要查询的客户ID。然后我们创建了一个SqlCommand对象,并将参数化查询语句和SqlConnection对象传递给它。
接下来,我们使用Parameters.AddWithValue方法为'@customerId”参数设置了一个值,这个值是字符串'ALFKI”。最后,我们使用SqlDataAdapter对象将查询结果填充到DataSet中,从而完成了一个安全的、不容易遭受SQL注入攻击的查询。