简体   繁体   English

如何使用C#在mysqlcommand中使用通配符%

[英]How to use the wildcard% in mysqlcommand using c#

Please help me guys, my professor has done this before but I forgot how. 请帮助我,我的教授以前做过,但是我忘了怎么做。 And if possible I need it right now. 如果可能,我现在需要它。 How do I use the wildcard % in this code? 如何在此代码中使用通配符%? Thanks in advance!! 提前致谢!!

MySqlCommand SelectCommand = new MySqlCommand("select * from sms.members where memberFName +' '+ memberLName like'" +cmbmemsched.Text+ "';", myconn);

You'd better use parameterized queries to avoid SQL injection: 您最好使用参数化查询来避免SQL注入:

MySqlCommand selectCommand = new MySqlCommand(
    "SELECT * FROM sms.members WHERE memberFName LIKE @memberFName;", 
    myconn
);
selectCommand.Parameters.AddWithValue(@memberFName, "%" + cmbmemsched.Text + "%");

In this example, the LIKE statement will look for the search phrase anywhere in the middle of the value. 在此示例中,LIKE语句将在值中间的任何位置查找搜索词组。 If you want to look for records that start with or end with the specified filter you will need to adapt the % in the parameter. 如果要查找以指定过滤器开头或结尾的记录,则需要调整参数中的%

I'd also more than strongly recommend you wrapping your IDisposable resources such as SQL commands in using statement to ensure that they are properly disposed even if some exceptions are thrown: 我还强烈建议您在using语句中包装IDisposable资源(例如SQL命令),以确保即使抛出某些异常也可以正确处理它们:

using (MySqlCommand selectCommand = new MySqlCommand("SELECT * FROM sms.members WHERE memberFName LIKE @memberFName;", myconn))
{
    selectCommand.Parameters.AddWithValue(@memberFName, "%" + cmbmemsched.Text + "%");
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM