使用LIKE的SQL选择查询

5

我正在尝试运行这段代码

 public long getTopicCountWithTag(String tag)
    {
        long count;
        query = " SELECT count(*) FROM [DB_us2].[dbo].[discns] where tags like '%@tags%'";
        try
        {
            com = new SqlCommand(query, con);
            com.Parameters.AddWithValue("@tags", tag);
            con.Open();          
            sdr = com.ExecuteReader();
            sdr.Read();
            count= sdr.GetInt32(0);

        }
        catch (Exception e)
        {
            count = -1;
            throw e;
        }
        finally
        {
            con.Close();
        }
        return count;
    }

它给出的输出是0。因此,我尝试找出问题并在管理工作室上运行示例查询,但输出不同,它给出了1。经过尝试所有排列组合,我认为问题可能出现在该语句中com.Parameters.AddWithValue("@tags", tag); 可能会出现@tags在查询中未被替换的情况。


如果您暂时将查询更改为= @tags,我认为问题出在“%tags%”语法上,请参阅此问题以进行进一步阅读:http://stackoverflow.com/questions/14222900/sql-like-query-to-c-sharp-code - JsonStatham
3个回答

10

我认为您的查询应该是

string query = "SELECT count(*) FROM [DB_us2].[dbo].[discns] where tags like @tags";

并将通配符添加到参数中

com.Parameters.AddWithValue("@tags", "%" + tag + "%");

你好,kaf。你的答案是正确的,但为什么它不能与上面的代码一起工作?有什么问题吗? - Hot Cool Stud
不幸的是,这是一个糟糕的建议... 如果标签变量取以下值 "'; GO; drop table [DB_us2].[dbo].[discns];" 会发生什么? - Yaugen Vlasau
@YaugenVlasau:这里有什么不好的建议吗? - Kaf
SQL注入是可能的。 - Yaugen Vlasau
4
参数化查询的整个思想是为了防止SQL注入,而您表示相反。通过参数传递的值不会被视为SQL语句进行评估。OP没有运行动态SQL。 - Kaf

0
query = " SELECT count(*) FROM [DB_us2].[dbo].[discns] where tags like '%'+ @tags + '%'";

并且保持一切不变。


0

应该是

 AddWithValue("@tags", "%" + tag + "%");

你必须将 %s 放在 AddWithValue 内部


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接