在C#項(xiàng)目中,應(yīng)對SQL注入問題的最佳方法是使用參數(shù)化查詢(Parameterized Query)或預(yù)編譯語句(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))
{
// 添加參數(shù)并設(shè)置值
command.Parameters.AddWithValue("@username", userInputUsername);
command.Parameters.AddWithValue("@password", userInputPassword);
connection.Open();
using (SqlDataReader reader = command.ExecuteReader())
{
// 處理查詢結(jié)果
}
}
}
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))
{
// 創(chuàng)建參數(shù)并設(shè)置值
SqlParameter usernameParam = new SqlParameter("@username", SqlDbType.VarChar);
usernameParam.Value = userInputUsername;
SqlParameter passwordParam = new SqlParameter("@password", SqlDbType.VarChar);
passwordParam.Value = userInputPassword;
// 將參數(shù)添加到命令中
command.Parameters.Add(usernameParam);
command.Parameters.Add(passwordParam);
connection.Open();
using (SqlDataReader reader = command.ExecuteReader())
{
// 處理查詢結(jié)果
}
}
}
安裝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 });
// 處理查詢結(jié)果
}
通過使用參數(shù)化查詢或預(yù)編譯語句,您可以有效地防止SQL注入攻擊,因?yàn)閰?shù)值會被自動轉(zhuǎn)義,而不是直接插入到SQL語句中。