在C#中,param關鍵字用于定義方法的參數。在防止SQL注入的上下文中,使用參數化查詢(Parameterized Query)是一種有效的方法。參數化查詢可以確保用戶輸入的數據與SQL命令本身分開,從而避免潛在的SQL注入攻擊。
以下是一個使用參數化查詢來防止SQL注入的C#示例:
using System.Data.SqlClient;
string connectionString = "your_connection_string";
string userInput = "user_input"; // 假設這是用戶輸入的數據
// 使用參數化查詢
string query = "SELECT * FROM Users WHERE Username = @username";
using (SqlConnection connection = new SqlConnection(connectionString))
{
using (SqlCommand command = new SqlCommand(query, connection))
{
// 添加參數并設置值
command.Parameters.Add("@username", SqlDbType.VarChar).Value = userInput;
connection.Open();
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
// 處理查詢結果
}
}
}
}
在這個示例中,我們使用@username參數代替了直接將用戶輸入拼接到SQL查詢字符串中。然后,我們使用command.Parameters.Add()方法將參數添加到SqlCommand對象中,并設置其值為用戶輸入的數據。這樣,用戶輸入的數據將被視為參數值,而不是SQL命令的一部分,從而避免了SQL注入攻擊。