实现C#安全的SQL查询防止注入的方法
导读:在C#中,为了防止SQL注入攻击,可以使用参数化查询(Parameterized Query)或存储过程(Stored Procedure) 参数化查询: using System; using System.Data.SqlClien...
在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)
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语句的结构。
声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942#qq.com核实处理,我们将尽快回复您,谢谢合作!
若转载请注明出处: 实现C#安全的SQL查询防止注入的方法
本文地址: https://pptw.com/jishu/696440.html
