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?