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
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";
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%";