5

I am trying to run this code

 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;
    }

its giving output 0 . So i try figure out what is the problem and run sample query on management studio but output is different its giving 1. After trying all permutation combination, i think problem is with this statement com.Parameters.AddWithValue("@tags", tag); might be possible @tags is not replaced in query.

1
  • What happens if you temporarily change the query to = @tags, i think the issue is with the '%tags%' syntax, see this question for further reading: stackoverflow.com/questions/14222900/… Commented Oct 25, 2013 at 8:03

3 Answers 3

10

I think your query should be

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

And add the wildcard to the parameter

com.Parameters.AddWithValue("@tags", "%" + tag + "%");
Sign up to request clarification or add additional context in comments.

5 Comments

hello kaf your answer is correct but why its not working with above code whats wrong in that.
unfortunatelli it is a bad advice... what happen if the tag variable takes the following value "'; GO; drop table [DB_us2].[dbo].[discns];"?
@YaugenVlasau: What is the bad advice here?
SQL injection is possible
@YaugenVlasau: The whole idea of parameterised query is to stop sql injection and you are saying otherwise. Values passed through parameters are not evaluate as sql. OP is not running dynamic sql.
0

Should be

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

you have to bring %s inside AddWithValue

Comments

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

and leave everething as it was.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.