溫馨提示×

實現(xiàn)C#安全的SQL查詢防止注入的方法

c#
小樊
82
2024-08-28 10:51:11
欄目: 云計算

在C#中,為了防止SQL注入攻擊,可以使用參數(shù)化查詢(Parameterized Query)或存儲過程(Stored Procedure)

  1. 參數(shù)化查詢:
using System;
using System.Data.SqlClient;

class Program
{
    static void Main()
    {
        string connectionString = "your_connection_string";
        string userInput = "user_input";

        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            connection.Open();

            using (SqlCommand command = new SqlCommand("SELECT * FROM Users WHERE Username = @Username", connection))
            {
                // 添加參數(shù)
                command.Parameters.AddWithValue("@Username", userInput);

                using (SqlDataReader reader = command.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        Console.WriteLine($"User ID: {reader["UserID"]}, Username: {reader["Username"]}");
                    }
                }
            }
        }
    }
}
  1. 存儲過程:

首先,在數(shù)據(jù)庫中創(chuàng)建一個存儲過程:

CREATE PROCEDURE GetUserByUsername
    @Username NVARCHAR(50)
AS
BEGIN
    SELECT * FROM Users WHERE Username = @Username;
END

然后,在C#代碼中調(diào)用該存儲過程:

using System;
using System.Data.SqlClient;

class Program
{
    static void Main()
    {
        string connectionString = "your_connection_string";
        string userInput = "user_input";

        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            connection.Open();

            using (SqlCommand command = new SqlCommand("GetUserByUsername", connection))
            {
                command.CommandType = System.Data.CommandType.StoredProcedure;

                // 添加參數(shù)
                command.Parameters.AddWithValue("@Username", userInput);

                using (SqlDataReader reader = command.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        Console.WriteLine($"User ID: {reader["UserID"]}, Username: {reader["Username"]}");
                    }
                }
            }
        }
    }
}

這兩種方法都可以有效地防止SQL注入攻擊。參數(shù)化查詢和存儲過程都會將用戶輸入作為參數(shù)傳遞,而不是直接拼接到SQL語句中。這樣,攻擊者無法通過輸入惡意內(nèi)容來改變原始SQL語句的結(jié)構(gòu)。

0