简体   繁体   中英

Adding parameters with sqlcommand.parameters.addwithvalue

I am not able to get any response from the following code:

using (SqlCommand cmd = new SqlCommand(@"SELECT * FROM users WHERE @parameter LIKE @value", con))
{
    cmd.Parameters.AddWithValue("parameter", parameter);
    cmd.Parameters.AddWithValue("value", value);

    SqlDataReader result = cmd.ExecuteReader();

    return result.HasRows;
}

Getting false every time.

Anyone knows why?

This is incorrect syntax in SQL

SELECT * FROM users WHERE @parameter LIKE @value

should be something like

SELECT * FROM users WHERE parameter = @parameter LIKE @value

and to add the LIKE parameter do this

cmd.Parameters.AddWithValue("@value","%" + value + "%");

cmd.Parameters.AddWithValue("parameter", parameter);

SqlCommand will infer that parameter is a string and so will quote it resulting in:

SELECT * FROM users WHERE 'xxx' LIKE 'yyy'

Which is going to be false.

Add the field name via (sanitized) string.format/concatenation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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