Say I have a basic query, something like this:
SELECT holiday_name
FROM holiday
WHERE holiday_name LIKE %Hallow%
This executes fine in m
The %
s should be part of the search string, not the query.
string CommandText = "SELECT holiday_name "
+ "FROM holiday "
+ "WHERE holiday_name LIKE @name";
Connection = new SqlConnection(ConnectionString);
try
{
Connection.Open();
Command = new SqlCommand(CommandText, Connection);
string name = "%" + HolidayTextBox.Text + "%";
Command.Parameters.Add(new SqlParameter("@name", name));
whatever you do don't do this:
string CommandText = "SELECT holiday_name "
+ "FROM holiday "
+ "WHERE holiday_name LIKE '%'" + HolidayTextBox.Text + "'%'";
as that will open you up to sql injection, instead do this:
Command.Parameters.Add(new SqlParameter("@name", "%" + HolidayTextBox.Text + "%"));
you may like to know about Command.Parameters.AddWithValue, e.g:
Command.Parameters.AddWithValue("@name", "%" + HolidayTextBox.Text + "%");
First off, your SqlParameter
name is @name
not name
.
Second, I would move your wildcards.
So it would look like this:
string CommandText = "SELECT holiday_name "
+ "FROM holiday "
+ "WHERE holiday_name LIKE @name;"
Connection = new SqlConnection(ConnectionString);
try
{
var escapedForLike = HolidatyTextBox.Text; // see note below how to construct
string searchTerm = string.Format("%{0}%", escapedForLike);
Connection.Open();
Command = new SqlCommand(CommandText, Connection);
Command.Parameters.Add(new SqlParameter("@name", searchTerm));
var results = Command.ExecuteScalar();
}
Note that LIKE
requires special care when passing parameters and you need to escape some characters Escaping special characters in a SQL LIKE statement using sql parameters.