In the use of preparedstatement to make a vague query to waste some of the trouble, has not paid attention to this problem. In general, we make an exact query, similar to the SQL statement: SELECT * FROM table where name =?, and then call PreparedStatement's setstring and other methods. The specified value. Then how to write vague query. I first tried: Select *from customer where name like '%?% '.
The program now complains because. is enclosed in single quotes, PreparedStatement does not regard it as a parameter. Later on the Internet to check some of the relevant information, found that you can write select * from table where the name like. , but when the parameters are specified. Specified as "%" +name+ "%", name is the specified query condition. That's OK.
Under normal circumstances, I always have the subconscious cognizance. is to replace the specified parameter, but we can actually package the specified parameters and then pass it to them. , for example, we add a% before and after the parameter, and then we pass it back.
String expr = "SELECT * from table where URL is like?";
Pstmt =con.preparestatement (expr);
String a= "a";
Pstmt.setstring (1, "%" +a+ "%");//Automatically add single quotes (package parameters)
Pstmt.execute ();
System.out.println (pstmt.tostring ())//Print SQL
//will default generate Sql:select *from table where URL like '%http% '
Reference connection: Click to open link