在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語句的結構。