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

   2024-09-30 3580
核心提示:在C#中,为了防止SQL注入攻击,可以使用参数化查询(Parameterized Query)或存储过程(Stored Procedure)参数化查询:using Sy

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

参数化查询:
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"]}");                    }                }            }        }    }}
存储过程:

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

CREATE PROCEDURE GetUserByUsername    @Username NVARCHAR(50)ASBEGIN    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语句的结构。

 
举报打赏
 
更多>同类网点查询
推荐图文
推荐网点查询
点击排行

网站首页  |  关于我们  |  联系方式网站留言    |  赣ICP备2021007278号