According to the general idea, we will write
Copy the Code 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 the Code as follows:
1 String searchName = "Sam ";
2 String strSql = "select * FROM Table1 where Name like @ Name ";
3 searchName = "%" + searchName + "%"; // note that no single quotation marks are required. parameters are automatically added to the SQL statement when they are passed to the SQL statement.
4 SqlParameter [] parameters = {
5 new SqlParameter ("@ Name", searchName)
6 };
Another method "select * FROM Table1 where Name like '%' + @ Name + '%'" can also solve the problem!