溫馨提示×

C#中SqlParameter如何防止SQL注入

c#
小樊
105
2024-09-23 21:23:50
欄目: 云計算

在C#中,使用SqlCommand對象的SqlParameter對象可以有效防止SQL注入攻擊。當你使用參數化查詢時,參數值會被自動轉義,從而避免了惡意用戶輸入導致的安全問題。

以下是如何使用SqlParameter來防止SQL注入的示例:

using System.Data;
using System.Data.SqlClient;

class SqlInjectionExample
{
    static void Main()
    {
        string userId = "userInput"; // 這里的用戶輸入可能包含惡意SQL代碼
        string connectionString = "YourConnectionString";
        string queryString = "SELECT * FROM Users WHERE UserId = @UserId";

        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            SqlCommand command = new SqlCommand(queryString, connection);
            command.Parameters.AddWithValue("@UserId", userId);

            try
            {
                connection.Open();
                SqlDataReader reader = command.ExecuteReader();
                while (reader.Read())
                {
                    Console.WriteLine($"User ID: {reader["UserId"]}, User Name: {reader["UserName"]}");
                }
                reader.Close();
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error: {ex.Message}");
            }
        }
    }
}

在這個示例中,我們使用了參數化查詢(queryString中的@UserId),并將用戶輸入(userId)作為參數傳遞給SqlCommand對象。當執行查詢時,參數值會被自動轉義,從而避免了SQL注入攻擊。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女