在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语句中。
辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
推荐阅读: C# MethodInvoker委托怎么使用