Technology Sharing

C# method to verify whether the input statement contains SQL intrusion

2024-07-12

한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina

In order to verify whether the data entered by the user contains SQL injection attack statements in C# WinForms, you can use a variety of methods to detect and prevent SQL injection. The following are some common methods:

1. Use parameterized queries

Parameterized queries are a best practice for preventing SQL injection by passing user input as parameters to SQL queries instead of embedding it directly into the SQL string. This ensures that user input cannot be interpreted as SQL code.

  1. using System.Data.SqlClient;
  2. public void ExecuteQuery(string userInput)
  3. {
  4. string connectionString = "数据库连接字符串";
  5. string query = "SELECT * FROM Users WHERE Username = @Username";
  6. using (SqlConnection connection = new SqlConnection(connectionString))
  7. using (SqlCommand command = new SqlCommand(query, connection))
  8. {
  9. command.Parameters.AddWithValue("@Username", userInput);
  10. connection.Open();
  11. SqlDataReader reader = command.ExecuteReader();
  12. while (reader.Read())
  13. {
  14. // Process the data
  15. }
  16. }
  17. }

2. Check for dangerous characters in user input

Common SQL injection characters and keywords, such as single quotes ('),Double quotes ("), semicolon (;), annotation symbol (--), as well as common SQL keywords such as SELECTINSERTDELETEUPDATEDROP etc).

  1. public bool IsSqlInjection(string input)
  2. {
  3. string[] sqlCheckList = { "SELECT", "INSERT", "UPDATE", "DELETE", "DROP", "--", ";", "'" };
  4. foreach (string item in sqlCheckList)
  5. {
  6. if (input.IndexOf(item, StringComparison.OrdinalIgnoreCase) >= 0)
  7. {
  8. return true;
  9. }
  10. }
  11. return false;
  12. }
  13. string userInput = txtUserInput.Text;
  14. if (IsSqlInjection(userInput))
  15. {
  16. MessageBox.Show("输入包含不安全的字符,请重新输入。");
  17. }
  18. else
  19. {
  20. // 继续处理用户输入
  21. ExecuteQuery(userInput);
  22. }

3. Use an ORM framework

Using an ORM (Object Relational Mapping) framework, such as Entity Framework, can greatly reduce the risk of SQL injection because the ORM framework automatically handles parameterized queries.

  1. using (var context = new YourDbContext())
  2. {
  3. var user = context.Users.SingleOrDefault(u => u.Username == userInput);
  4. if (user != null)
  5. {
  6. // Process the user data
  7. }
  8. }