在C#項目中,應對SQL注入問題的最佳方法是使用參數化查詢(Parameterized Query)或預編譯語句(Prepared Statement)
using System.Data.SqlClient;
string connectionString = "your_connection_string";
string sqlQuery = "SELECT * FROM Users WHERE Username = @username AND Password = @password";
using (SqlConnection connection = new SqlConnection(connectionString))
{
using (SqlCommand command = new SqlCommand(sqlQuery, connection))
{
// 添加參數并設置值
command.Parameters.AddWithValue("@username", userInputUsername);
command.Parameters.AddWithValue("@password", userInputPassword);
connection.Open();
using (SqlDataReader reader = command.ExecuteReader())
{
// 處理查詢結果
}
}
}
using System.Data.SqlClient;
string connectionString = "your_connection_string";
string sqlQuery = "SELECT * FROM Users WHERE Username = @username AND Password = @password";
using (SqlConnection connection = new SqlConnection(connectionString))
{
using (SqlCommand command = new SqlCommand(sqlQuery, connection))
{
// 創建參數并設置值
SqlParameter usernameParam = new SqlParameter("@username", SqlDbType.VarChar);
usernameParam.Value = userInputUsername;
SqlParameter passwordParam = new SqlParameter("@password", SqlDbType.VarChar);
passwordParam.Value = userInputPassword;
// 將參數添加到命令中
command.Parameters.Add(usernameParam);
command.Parameters.Add(passwordParam);
connection.Open();
using (SqlDataReader reader = command.ExecuteReader())
{
// 處理查詢結果
}
}
}
安裝Dapper NuGet包:
Install-Package Dapper
示例代碼:
using System.Data.SqlClient;
using Dapper;
string connectionString = "your_connection_string";
string sqlQuery = "SELECT * FROM Users WHERE Username = @username AND Password = @password";
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
var queryResult = connection.Query(sqlQuery, new { username = userInputUsername, password = userInputPassword });
// 處理查詢結果
}
通過使用參數化查詢或預編譯語句,您可以有效地防止SQL注入攻擊,因為參數值會被自動轉義,而不是直接插入到SQL語句中。