C#中SqlParameter如何防止SQL注入

c#
小樊
81
2024-09-23 21:23:50
欄目: 云計(jì)算

在C#中,使用SqlCommand對(duì)象的SqlParameter對(duì)象可以有效防止SQL注入攻擊。當(dāng)你使用參數(shù)化查詢時(shí),參數(shù)值會(huì)被自動(dòng)轉(zhuǎn)義,從而避免了惡意用戶輸入導(dǎo)致的安全問(wèn)題。

以下是如何使用SqlParameter來(lái)防止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}");
            }
        }
    }
}

在這個(gè)示例中,我們使用了參數(shù)化查詢(queryString中的@UserId),并將用戶輸入(userId)作為參數(shù)傳遞給SqlCommand對(duì)象。當(dāng)執(zhí)行查詢時(shí),參數(shù)值會(huì)被自動(dòng)轉(zhuǎn)義,從而避免了SQL注入攻擊。

0