温馨提示×

C#中SqlParameter如何防止SQL注入

c#
小樊
81
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