简体   繁体   中英

SqlCommand with Parameters

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

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

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

Any idea why?

The "why?" is because very few movies have the word "@Search" in their name - ie "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 + '%'";

Or (preferably, IMO):

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

and add the % at the call-site:

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

Try this:

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

            }
        }
    }
}

I changed string sql , I think that it can help.

请勿使用单引号'@Search',因为它的作用类似于此处的变量。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM