【问题标题】:How to use the wildcard% in mysqlcommand using c#如何使用c#在mysqlcommand中使用通配符%
【发布时间】:2014-03-02 16:31:06
【问题描述】:

请帮帮我,我的教授以前做过,但我忘记了。如果可能的话,我现在就需要它。如何在此代码中使用通配符 %?提前致谢!!

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

【问题讨论】:

标签: c# wildcard


【解决方案1】:

最好使用参数化查询来避免 SQL 注入:

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

在此示例中,LIKE 语句将在值中间的任何位置查找搜索短语。如果要查找以指定过滤器开头或结尾的记录,则需要调整参数中的%

我还强烈建议您将 IDisposable 资源(例如 SQL 命令)包装在 using 语句中,以确保即使抛出一些异常也能正确处理它们:

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

【讨论】:

    猜你喜欢
    • 2012-02-24
    • 2017-08-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-24
    • 1970-01-01
    • 2020-04-11
    • 2023-04-01
    相关资源
    最近更新 更多