Using Prepatestatement in Java and like fuzzy queries

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.