MST

星途 面试题库

面试题:C#中代码安全性之防止SQL注入攻击

假设你正在开发一个使用SQL Server数据库的C#应用程序,用户输入用于构建SQL查询。详细说明如何在C#代码中有效防止SQL注入攻击,列举至少两种不同的防范方法并给出代码示例。
18.7万 热度难度
编程语言C#

知识考点

AI 面试

面试题答案

一键面试
  1. 使用参数化查询
    • 原理:参数化查询将SQL语句与参数分离,数据库引擎会分别处理它们,从而防止恶意用户通过输入特殊字符篡改SQL逻辑。
    • 代码示例
using System;
using System.Data.SqlClient;

class Program
{
    static void Main()
    {
        string username = Console.ReadLine();
        string connectionString = "your_connection_string";
        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            string query = "SELECT * FROM Users WHERE UserName = @UserName";
            using (SqlCommand command = new SqlCommand(query, connection))
            {
                command.Parameters.AddWithValue("@UserName", username);
                try
                {
                    connection.Open();
                    SqlDataReader reader = command.ExecuteReader();
                    while (reader.Read())
                    {
                        Console.WriteLine(reader["UserID"]);
                    }
                }
                catch (SqlException ex)
                {
                    Console.WriteLine("SQL error: " + ex.Message);
                }
            }
        }
    }
}
  1. 使用存储过程
    • 原理:存储过程在数据库中预编译并存储,传入的参数会被正确处理,降低了SQL注入风险。
    • 代码示例
    • 首先在SQL Server中创建存储过程:
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 username = Console.ReadLine();
        string connectionString = "your_connection_string";
        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            using (SqlCommand command = new SqlCommand("GetUserByUsername", connection))
            {
                command.CommandType = System.Data.CommandType.StoredProcedure;
                command.Parameters.AddWithValue("@UserName", username);
                try
                {
                    connection.Open();
                    SqlDataReader reader = command.ExecuteReader();
                    while (reader.Read())
                    {
                        Console.WriteLine(reader["UserID"]);
                    }
                }
                catch (SqlException ex)
                {
                    Console.WriteLine("SQL error: " + ex.Message);
                }
            }
        }
    }
}