SqlCommand时使用的参数参数、SqlCommand

2023-09-03 06:52:49 作者:''__夏 末

我做从SQL Server表中选择与此code:

I make a selection from a SQL Server table with this code:

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())
            {
                ....
            }
        }
    }
}

和它完美的作品,但我想prevent SQL注入,所以我尝试使用:

And it works perfectly, but I want to prevent SQL Injections, so I try to use:

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。

And when I try to execute this I get no results from SQL Server.

任何想法,为什么?

推荐答案

在为什么呢?是因为很少有电影有单词@Search在他们的名字 - 也就是印第安纳琼斯和最后的@Search。也许星际迷航三:@Search对于斯波克。通过将其括在单引号,你正在寻找的文字串 @Search ,而不是参数的值称为 @Search 的。

The "why?" is because very few movies have the word "@Search" in their name - i.e. "Indiana Jones and the Last @Search". Maybe "Star Trek III: The @Search For Spock". By enclosing it in single quotes, you are looking for the literal string @Search, rather than the value of the parameter called @Search.

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

或(preferably,IMO):

Or (preferably, IMO):

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

和添加在调用现场:

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