user3383093
user3383093

Reputation: 19

How to use like operator with %?

I am creating a search bar and I am having a hard time constructing the correct query for that. Here is my code:

SqlCommand command1 = new SqlCommand(
    "Select * from tbl_customer where customer_name like '%''"+ textBox1.Text +"''%' ",
    MySqlConnection);

Upvotes: 0

Views: 107

Answers (3)

Arunprasanth K V
Arunprasanth K V

Reputation: 21901

SqlCommand command1 = new SqlCommand(
    "Select * from table-name where column-name like '%"+ textboxid.Text +"%' ",
    MySqlConnection);

If u making a sample program then ok it will work ,but if you are looking for a professional use software or website then don't go with this method . Check sql injection because here you are directly adding the control values in query

Upvotes: 0

F0r3v3r-A-N00b
F0r3v3r-A-N00b

Reputation: 3003

SqlCommand command1 = new SqlCommand("Select * from tbl_customer where customer_name like @search_value", MySqlConnection);
command1.Parameters.AddWithValue("@search_value","%" + textBox1.Text + "%");

Upvotes: 2

rikitikitik
rikitikitik

Reputation: 2450

You are adding too many 's.

SqlCommand command1 = new SqlCommand(
    "Select * from tbl_customer where customer_name like '%"+ textBox1.Text +"%' ",
    MySqlConnection);

Note that I have removed the extra 's after the first % and before the last %.

However, you should be careful about SQL injection and use parameters instead of directly adding control values into your query.

Upvotes: 1

Related Questions