gpt4 book ai didi

c# - 带参数的 SqlCommand

转载 作者:太空宇宙 更新时间:2023-11-03 19:08:59 24 4
gpt4 key购买 nike

我使用以下代码从 SQL Server 表中进行选择:

using (SqlConnection con = new SqlConnection(SqlConnectionString))
{
string sql = @"SELECT * FROM movies WHERE title like '%' + '" + searchQuery + "' + '%'";

using (var command = new SqlCommand(sql, con))
{
con.Open();

using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
....
}
}
}
}

它工作得很好,但我想防止 SQL 注入(inject),所以我尝试使用:

using (SqlConnection con = new SqlConnection(SqlConnectionString))
{
string sql = @"SELECT * FROM movies WHERE title like '%' '@Search' + '%'";

using (var command = new SqlCommand(sql, con))
{
command.Parameters.AddWithValue("@Search", searchQuery);
con.Open();

using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
..........
}
}
}
}

当我尝试执行此操作时,我没有从 SQL Server 获得任何结果。

知道为什么吗?

最佳答案

“为什么?”是因为很少有电影的名称中包含“@Search”一词 - 即“Indiana Jones and the Last @Search”。也许是“星际迷航 III:@Search For Spock”​​。通过将其括在单引号中,您正在查找文字字符串 @Search,而不是名为 @Search 的参数的值。

string sql = @"SELECT * FROM movies WHERE title like '%' + @Search + '%'";

或者(最好是 IMO):

string sql = @"SELECT * FROM movies WHERE title like @Search";

并在调用处添加%:

command.Parameters.AddWithValue("Search", "%" + searchQuery + "%");

关于c# - 带参数的 SqlCommand,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22660590/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com