Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / database / MySQL

MySqlCommand, MySqlParameter and LIKE with Percent Symbol

5.00/5 (1 vote)
5 Aug 2013CPOL 33.4K  
How to search text with LIKE with MySQLParameter in MySQL .NET / Connector

Introduction

Using GetSqlStringCommand with a text comparative, with LIKE, in ADO.NET and the MySqlParamenter gets you different results between executing by hand the command in a MySQL client and executing it through ADO.NET.

Background

This occurs when you write a command like this "SELECT * FROM users WHERE name LIKE '%John%'", this will return:

John Frank
Johnny Philips
H. F. John

But for ADO.NET if you set a var, like "@name" and update the command like this "SELECT * FROM users WHERE name LIKE '%@name%'", ADO.NET treats it as the string '@name' you will return 0 result, because there does not exist any user with the name @name or the email @name, but yes someone with an email of the domain "name.com", like alberto@name.com, but this is a casualty and not, what we expect.

So you need to remove the simple quota and set the value appending and preceding with "%".

Using the Code

C#
//Wrong way
MySqlCommand cmd = oldDb.GetSqlStringCommand(CommandType.Text,"SELECT * _
FROM users WHERE name LIKE '%@name%'");
MySqlParameter nameParameter= cmd.CreateParameter();
nameParameter.DbType = DbType.String;
nameParameter.ParameterName = "@name";
nameParameter.Value = "John";

//Good way
MySqlCommand cmd = oldDb.GetSqlStringCommand(CommandType.Text,"SELECT * _
FROM users WHERE name LIKE @searchText");
MySqlParameter nameParameter= cmd.CreateParameter();
nameParameter.DbType = DbType.String;
nameParameter.ParameterName = "@searchText"
nameParameter.Value = "%John%"; 

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)