According to the general idea, we will write
CopyCodeThe Code is as follows: String searchname = "Sam ";
String strsql = "select * From Table1 where name like '% @ name % '";
Sqlparameter [] parameters = {
New sqlparameter ("@ name", searchname)
};
However, the result is that no query results are found, no error is found in the trace code, and you do not want to concatenate strings (to prevent attacks ). So we tracked SQL Execution and found that SQL automatically added single quotation marks to parameters.
In fact, in SQL, the like code is parsed into like '% 'Sam' % '. Therefore, you cannot find the desired result.
Therefore, we can change the code:Copy codeThe Code is as follows: String searchname = "Sam ";
String strsql = "select * From Table1 where name like @ name ";
Searchname = "%" + searchname + "%"; // note that no single quotation marks are required. parameters are automatically added to the SQL statement if they are passed to the SQL statement.
Sqlparameter [] parameters = {
New sqlparameter ("@ name", searchname)
};
In this way, the desired query result can be reached.