Introduction

Using GetSqlStringCommand with a text comparative, with LIKE, in ADO.NET and the MySQLParamenter gets you different result 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:

Copy Code
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 no exists 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 

Copy Code
//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 @name");
MySQLParameter nameParameter= cmd.CreateParameter();
nameParameter.DbType = DbType.String;
nameParameter.ParameterName = "@searchText"
nameParameter.Value = "%John%"; 

相关文章:

  • 2021-07-04
  • 2021-05-31
  • 2021-12-02
  • 2021-12-20
  • 2022-12-23
  • 2022-02-08
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2022-02-02
  • 2021-11-12
  • 2021-12-11
  • 2021-06-24
  • 2022-12-23
相关资源
相似解决方案