How to prevent SQL injection in C#?
In C#, parameterized queries can be used to prevent SQL injection. Parameterized queries involve separating query parameters from the SQL statement, ensuring that input values are properly encoded before being passed to the database.
Here is an example of using parametrized query:
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
string query = "SELECT * FROM Users WHERE Username = @Username AND Password = @Password";
SqlCommand command = new SqlCommand(query, connection);
// 添加参数并设置值
command.Parameters.AddWithValue("@Username", username);
command.Parameters.AddWithValue("@Password", password);
SqlDataReader reader = command.ExecuteReader();
// 处理查询结果
while (reader.Read())
{
// 处理每一行数据
}
}
In the above example, the Parameters.AddWithValue method of the SqlCommand class is used to add parameters. This ensures that the values of the parameters are properly encoded, preventing SQL injection attacks.
It is recommended to always use parameterized queries to execute database operations, as they not only prevent SQL injection but also improve query performance and allow for the reuse of compiled query plans when executing the same query multiple times.