Search code examples
javasqlparametersparameter-passingprepared-statement

How to use placeholders in like clause in SQL query?


This is my query:

 select * from Table1 where Identifier = 'ABC' and Identifier_Type like ':name%:id' 

can I change this to,

 select * from Table1 where Identifier = 'ABC' and Identifier_Type like '?%?'  

will it work? I have to use these parameters in the prepared statement so I thought of replacing the named parameters with the placeholders '?'.. will it work like this '?%?'


Solution

  • Query Should be like this::

        PreparedStatement pstmt = con.prepareStatement ("Select * 
        from 
        Table1 where Identifier = 'ABC' and Identifier_Type  like?");
    

    While setting in prepared statement:

       pstmt.setString(1, "%" + data + "%"); // where data is string Variable
    

    OR By using SQL function

       PreparedStatement pstmt = con.prepareStatement(
      "select * from Table1 where Identifier = 'ABC' and Identifier_Type  
        like  CONCAT( '%',?,'%')";
         
         pstmt.setString(1, data); // Where data is String variable