MySQL:System.Data.Entity ,MySqlCommand, MySqlParameter and "LIKE" %
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:
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
//错误写法
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 @name");
MySQLParameter nameParameter= cmd.CreateParameter();
nameParameter.DbType = DbType.String;
nameParameter.ParameterName = "@searchText"
nameParameter.Value = "%John%"; 补充说明:即使在变量值前后,加上百分比%
最新文章
- Oracle索引梳理系列(五)- Oracle索引种类之表簇索引(cluster index)
- C#字符串的方法
- C#中获取当前时间:System.DateTime.Now.ToString()用法
- Java对象的序列化和反序列化
- Sqli-LABS通关笔录-17-审计SQL注入
- yum源的修改
- C:\Windows\system32\config\systemprofile\AppData\Local\Microsoft\Team Foundation\4.0\Cache\VersionControl.config is not valid and cannot be loaded.
- 初学java,遇到的陌生词语(1)
- 天津Uber优步司机奖励政策(1月25日~1月31日)
- 转:15 Best Responsive Web Design Testing Tools
- Serializable在C#中的作用——.net中的对象序列化
- Java的跨平台原理
- poj1797 Heavy Transportation Dijkstra算法的简单应用
- 电梯调度二——曹玉松&;&;蔡迎盈
- 2018-2019-2 网络对抗技术 20165317 Exp4 恶意代码分析
- ABP 设置默认为中文
- geopandas overlay 函数报错问题解决方案
- 【Java】-NO.16.EBook.4.Java.1.004-【疯狂Java讲义第3版 李刚】- 内部类
- sql server web管理软件
- 20155325 信息安全技术 实验二 Windows口令破解