温馨提示×

实现C#安全的SQL查询防止注入的方法

c#
小樊
129
2024-08-28 10:51:11
栏目: 云计算

在C#中,为了防止SQL注入攻击,可以使用参数化查询(Parameterized Query)或存储过程(Stored Procedure)

  1. 参数化查询:
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))
            {
                // 添加参数
                command.Parameters.AddWithValue("@Username", userInput);

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

首先,在数据库中创建一个存储过程:

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

然后,在C#代码中调用该存储过程:

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;

                // 添加参数
                command.Parameters.AddWithValue("@Username", userInput);

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

这两种方法都可以有效地防止SQL注入攻击。参数化查询和存储过程都会将用户输入作为参数传递,而不是直接拼接到SQL语句中。这样,攻击者无法通过输入恶意内容来改变原始SQL语句的结构。

0