You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改SQL LIKE表达式实现关键词首字母匹配查询?

修改SQL模糊查询为首字母匹配的方法

1. 直接修改LIKE表达式

要实现首字母匹配,只需把原SQL语句中的LIKE '%{0}%'修改为LIKE '{0}%'——去掉开头的%,保留结尾的%,就能匹配所有以sub_cat值开头的Keyword记录。

修改后的SQL语句片段:

string sqlQuery = string.Format("select Keyword from RR_PRIAM where Keyword LIKE '{0}%'", sub_cat);

2. 必须修复的SQL注入风险

原代码用string.Format直接拼接用户输入到SQL语句中,存在严重的SQL注入漏洞,攻击者可构造恶意输入篡改SQL逻辑,引发数据泄露或破坏。正确做法是使用参数化查询,完整安全代码如下:

List<string> Cat = new List<string>();
string maincon = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;

using (SqlConnection con = new SqlConnection(maincon))
{
    string sqlQuery = "select Keyword from RR_PRIAM where Keyword LIKE @SubCat + '%'";
    
    con.Open();
    using (SqlCommand cmd = new SqlCommand(sqlQuery, con))
    {
        cmd.Parameters.AddWithValue("@SubCat", sub_cat);
        
        using (SqlDataReader sdr = cmd.ExecuteReader())
        {
            while (sdr.Read())
            {
                Cat.Add(sdr.GetString(0));
            }
        }
    }
}
return Cat;

代码中用@SubCat作为参数占位符,通过SqlParameter传递用户输入,同时用@SubCat + '%'实现首字母匹配,既满足需求又彻底规避注入风险。另外using语句能自动释放数据库连接、命令和阅读器资源,无需手动调用Close()。

内容的提问来源于stack exchange,提问作者peermohamed s

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 19:06:20