How to use sql parameters for a select query?

前端 未结 3 977
孤城傲影
孤城傲影 2021-01-21 07:59

I need to fetch the records based on a \'like\' match against a set of records,

The below query im using is not working . Does anyone knows what\'s wrong with the query?

3条回答
  •  天涯浪人
    2021-01-21 08:47

    What happens this way?

    sqlCommand.CommandText = "SELECT * FROM Customer WHERE Name LIKE @Name;";
    sqlCommand.Parameters.AddWithValue("@Name", "%" + searchString + "%");
    

    You could also code it as follows to avoid all the wildcard formatting in the first place:

    sqlCommand.CommandText = "SELECT * FROM Customer WHERE CHARINDEX(@Name, Name) > 0;";
    sqlCommand.Parameters.AddWithValue("@Name", searchString);
    

    If you're going to insist on doing it the unsafe way, at the very least double-up any single quotes found in searchString, e.g.

    searchString.Replace("'", "''")
    

提交回复
热议问题